建模两个依赖的类层次结构

时间:2017-10-25 10:14:18

标签: casting structure extend

我正面临一个模型探测器,我试图在这篇文章中尽可能地简化。

我考虑了一组扩展公共类的类(在这里称为Letter):

public abstract class Letter{
    public void commonMethod(){...}
}

public class A extends Letter{
    public void methodA(){...}
}

// Idem for several classes B, C, D, ...

我需要实现另一组类。它们中的每一个都包含一个Letter属性并扩展了相同的类(这里称为UsesLetter)。

以下是我目前的做法(但我想知道是否有更好的方法):

public abstract class UsesLetter{
    protected Letter l;

    public UsesLetter(Letter l){this.l = l;}
    public void commonMethod(){l.commonMethod();}
    public abstract void setLetterIfCompatible(Letter l);
}

public class UsesA extends UsesLetter{

    public UsesA(A a){super(l);}

    public void usesA(){((A)l).methodA();}

    @Override
    public boolean setLetterIfCompatible(Letter l){

        boolean result = false;
        if(l instanceof A){
            this.l = l;
        result = true;

        return result;

    }

    // Specific behavior of the class
    // ...

}

// Idem for several classes UsesA, UsesB, ...
// Note: several classes may use the same Letter class (e.g., UsesABis, UsesATer, ...)

// Example of use
public static void main(String[] args){

    UsesA ua = new UsesA(new A());
    UsesB ub = new UsesB(new B());

    // I want to be able to use the common and specific methods...
    ua.commonMethod();
    ua.usesA();
    ub.usesB();

    Letter l = new A();

    // ... and to change the letter
    if(ua.setLetterIfCompatible(l))
        ua.methodA();

}

我不相信这是实现我想要的行为的最佳方式,因为每次我想要使用它们时都需要输出字母。

您知道是否有更好的建模?也许是一种设计模式?

1 个答案:

答案 0 :(得分:1)

您可以使用泛型:

public abstract class UsesLetter<LetterType extends Letter>{
    protected LetterType l;

    public UsesLetter(LetterType l){this.l = l;}
    public void commonMethod(){l.commonMethod();}
    public abstract void setLetter(LetterType l);
}

public class UsesA extends UsesLetter<A>{

    public UsesA(A a){super(a);}

    public void useA(){((A)l).methodA();}

    @Override
    public void setLetter(A a){
        l = a;
    }

    // Specific behavior of the class
    // ...
}