开发者

Corresponding type trees

I'm wondering if there is some smart way to create 2 parallel type hierarchies in Java. For example I've got some XType. XType has its own tree of types (around 10-20, some flat, some going to 3 levels).

XType
\
 + AXType
 | \
 |  + AAXType
 |
 + BXType
 ......

Now I've got some situations where I'd like to have a corresponding hierarchy but with some additional property. So XTypeWithProperty, AXTypeWithProperty, ...

Now since there's only single inheritance, it's not possible for AAXTypeWithProperty to have parents AXTypeWithProperty and AAXType... Of course I could fold everything to the first tree with the XType at root and add a .getProperty() method that can return null for the types without it.

But I'd like to find a type-safe (as much as Java can manage) solution here. I thought about something like creating generic types XType<WithProperty> and XType<NoProperty> and operating with them... but it lo开发者_如何学编程oks like it would be a bit tedious to maintain.

Is there a better way?


You might be interested in the adapter pattern which may help you get around the issues of the fragile base class problem. Eclipse IDE uses this internally for, say, maintaining a Java model tree as well as a Resource model tree, and then adapting elements between the two trees. Alternatively, you could look at injection using Guice or AspectJ.


I'm afraid you will need to use delegation here. For instance:

public class WithProperty<T extends XType,P> {
    private T object;
    private P property;

    public WithProperty(T obj) {
        this.object = obj;
    }

    public T getObject() {
        return object;
    }

    public P getProperty() {
        return property;
    }

    public void setProperty(P property) {
        this.property = property;
    }
}


Basically, what you are talking about is a mix-in class.

In plain Java, mixins are not possible, the standard Java solution is to use the Strategy or Adapter patterns (see the other answers)

Or you can use AspectJ to generate "real" mixins

public interface Foo{
    void isItTrue();
}
public aspect MixinAspect{
  interface FooMixin extends Foo{}
  public void FooMixin.isItTrue(){
      System.out.println("Yup, I'm a mixin");
  }
  declare parents: com.yourpackage..* implements Mixin;
}

Now all classes in com.yourpackage implement Foo and share the same default behaviour.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜