我正在学习如何使用Factory模式在Java中创建对象。我想创建类来管理汽车。汽车可以是大号或小号。我创建了一个接口,该接口定义了要由实现类实现的方法。抽象类实现了小型和大型汽车共享的接口的一些常用方法。具体的SmallCar和LargeCar类实现了抽象类的其余方法。
汽车界面
public interface Car {
String getRegistrationNumber();
void drive();
}
抽象的汽车类别实现了汽车界面
public abstract class AbstractCar implements Car {
private final RegistrationNumber regNumber;
private boolean tankFull = true;
public AbstractCar(RegistrationNumber regNumber) {
this.regNumber = regNumber;
}
@Override
public final String getregistrationNumber() {
return regNumber.toString();
}
/**This method is not defined in the implemented Car interface. I added it to
*the abstract class because I want subclasses of these abstract class
*to have this method*/
public boolean isTankFull() {
return tankFull;
}
}
小型车扩展了抽象类
public final class SmallCar extends AbstractCar {
public SmallCar(RegistrationNumber regNum) {
super(regNum);
}
@Override
public void drive() {
//implemented here
}
}
工厂课:
此类负责创建特定类型汽车的实例。
public final class CarFactory {
public static Car createCar(String carType, RegistrationNumber regNum) {
Car car = null;
if (carType.equals("Small") {
car = new SmallCar(regNum);
}
return car;
}
主要方法
RegistrationNumber regNum = new RegistrationNumber('a', 1234);
Car c = CarFactory.createCar("Small", regNum);
c.getRegistrationNumber(); //this works
c.isTankFull(); //this instance of Car cannot access the isTankFull method defined on the abstract class. The method is not defined on the Car interface though. I do not understand why.
挑战在于,Car实例可以访问Car接口上定义的所有其他方法,但不能访问isTankFull()
抽象类上定义但接口上没有定义的方法。我希望我的解释很清楚。
之所以看不到该方法,是因为您的c
对象被声明为Car
接口。当然,当它从工厂方法中出来时,它是一个SmallCar
,但是您的变量中只有接口。您可以将声明更改为AbstractCar c = CarFactory.createCar("SmallCar", regnum);
。
您可以在使用接口时完成此操作的另一种方法是,在尝试访问不在接口上的方法时将c
对象转换为一个对象AbstractCar
,但是您需要小心,因为工厂总是有可能返回对象实现了Car
,但是没有实现AbstractCar
。
if (c instanceof AbstractCar) {
((AbstarctCar)c).isTankFull();
}
当然,另一种简单的解决方案是将方法添加到界面中,尽管这将消除此问题的教学机会。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句