您可以返回一个抽象类。有没有关于返回接口或抽象类的法律,它取决于你的软件设计:
一种方式来回报您的x
,y
,z
是使用Factory Pattern。
例(伪):
public class PQRFactory {
public PQR getPQR(condition) {
switch (condition) {
case condition_x :
return new x();
break;
case condition_y :
return new y();
break;
case condition_z :
return new z();
break;
default : return null;
}
}
}
如果你不想使用condition
那么你可以使用一个Builder pattern做什么@JVerstry公布。
当您的课程实施ABC
界面时,您可以使用Strategy pattern通过工厂供ABC
实施人员使用。
例(伪):
public abstract class AbstractABC implements ABC {
protected PQRFactory factory;
protected AbstractABC() {
factory = new PQRFactory();
}
protected AbstractABC(PQRFactory factory) {
this.factory = factory;
}
}
public class ABCImpl1 extends AbstractABC() {
//Override constructors needed to construct this class
}
希望这有助于。
只要确保在实现ABC的每个类中的returnRightClass()的每个实现都返回PQR(x,y或z)的正确实例。我该如何做到这一点 –
ohh yes ...是个白痴...... –
@Saurabh请参阅编辑我的答案 – JVerstry