正确的方法来实现继承

时间:2015-04-06 13:51:15

标签: java inheritance casting abstract-class

我有这个抽象类:FooAbstract,还有两个扩展它的类:FooSingleInstanceFooMultiInstances

public abstract class FooAbstract {
    private boolean single;

    public FooAbstract(boolean single) {
        this.single = single;
    }

    public boolean isSingle() {
        return single;
    }
}

public class FooSingleInstance extends FooAbstract {
    private Bar bar;

    public FooSingleInstance(boolean single) {
        super(single);
    }

    public Bar getBar() {
        return bar;
    }
}

public class FooMultiInstances extends FooAbstract {
    private Map<String, Bar> barMap;

    public FooMultiInstances(boolean single) {
        super(single);
    }

    public Bar getBarFromKey(String key) {
        return barMap.get(key);
    }
}

我有一个方法doSomethingWithBar(FooAbstract foo)

public void doSomethingWithBar(FooAbstract foo) {
    if (foo.isSingle()) {
        Bar bar = ((FooSingleInstance) foo).getBar();
        //do something with bar
    } else {
        //some logic to get key
        Bar bar = ((FooMultiInstances) foo).getBarFromKey(key);
        //do something with bar
    }
}

代码类型实现了我想要实现的目标,但我不认为它遵循编码原则。有没有更好的方法来实现这一目标?

3 个答案:

答案 0 :(得分:3)

您可以添加:

public abstract class FooAbstract{

    // add abstract method to get bar
    public abstract Bar getBar(String key);
}

并在FooSingleInstance&amp;中以不同方式实现它FooMultiInstances:

public class FooSingleInstance extends FooAbstract{
    private Bar bar;
    @Override
    public Bar getBar(String key) {
        return bar;
    }
}

public class FooMultiInstances extends FooAbstract{
    private Map<String, Bar> barMap;
    @Override
    public Bar getBar(String key) {
        return barMap.get(key);
    }
}

用法只是:

Bar bar=foo.getBar(key);

BTW我认为没有理由使用single字段。

答案 1 :(得分:3)

为什么关心您拥有哪种类型的Foo

上课并添加abstract方法:

public abstract class FooAbstract {
    public abstract Bar getInstance(String key);
}

现在,您可以根据需要在不同版本中实现该方法:

public class FooSingleInstance extends FooAbstract {

    private Bar bar;      

    @Override
    public Bar getInstance(String key) {
        return bar;
    }
}
public class FooMultiInstances extends FooAbstract {

    private Map<String, Bar> barMap;

    @Override
    public Bar getInstance(String key) {
        return barMap.get(key);
    }
}

现在你需要做的就是:

public void doSomethingWithBar(FooAbstract foo) {
    final Bar bar = foo.getInstance(key);
    //do something with bar
}

现在,鉴于您的FooAbstract没有变量或逻辑,将其设为interface可能是有意义的:

public interface BarFactory {
    Bar getInstance(String key);
}

答案 2 :(得分:2)

你可以像这样重载方法doSomethingWithBar:

public void doSomethingWithBar(FooSingleInstance foo) {

}

public void doSomethingWithBar(FooMultiInstances foo) {

}