我从这个链接中获取了工厂模式示例:http: //howtodoinjava.com/2012/10/23/implementing-factory-design-pattern-in-java/
但是,当我将代码复制到自己的 IDE 中时,我收到一条警告,说我的构造函数中有一个可覆盖的方法调用。我明白这意味着什么,我只是认为工厂模式应该解决这个问题?教程有问题吗?我应该做一些不同的事情吗?
我只包括了一种汽车类型,只是为了节省我粘贴的代码量:
类Car
:
package FactoryPattern;
public abstract class Car {
public Car(CarType model){
this.model = model;
arrangeParts();
}
private void arrangeParts(){
//Do one time processing herer
}
//Do subclass level processing in this method
protected abstract void construct();
private CarType model = null;
public CarType getModel(){
return model;
}
public void setModel (CarType model){
this.model = model;
}
}
类CarFactory
:
package FactoryPattern;
public class CarFactory {
public static Car buildCar(CarType model){
Car car = null;
switch (model) {
case SMALL:
car = new SmallCar();
break;
case SEDAN:
car = new SedanCar();
break;
case LUXURY:
car = new LuxuryCar();
break;
default:
//throw an exception
break;
}
return car;
}
}
类FactoryPattern
:
package FactoryPattern;
public enum CarType {
SMALL, SEDAN, LUXURY
}
package FactoryPattern;
public class LuxuryCar extends Car {
LuxuryCar(){
super(CarType.LUXURY);
construct();
}
@Override
protected void construct(){
System.out.println("Building Luxury Car");
}
}
类CarFactoryTest
:
package FactoryPattern;
public class CarFactoryTest {
public static void main(String[] args) {
CarFactory.buildCar(CarType.SMALL);
CarFactory.buildCar(CarType.SEDAN);
CarFactory.buildCar(CarType.LUXURY);
}
}