简介
简单工厂模式还是得修改factory类来构建出新的对象.
工厂方法模式将factory也抽象成一个抽象接口
code
public interface Car {
void name();
}
public interface CarFactory {
Car getCar();
}
public class Consumer {
public static void main(String[] args) {
Car c1 = new WuLingFactory().getCar();
Car c2 = new TeslaFactory().getCar();
c1.name();
c2.name();
}
}
public class Tesla implements Car {
@Override
public void name() {
System.out.println("特斯拉");
}
}
public class TeslaFactory implements CarFactory{
@Override
public Car getCar(){
return new Tesla();
}
}
public class WuLing implements Car {
@Override
public void name() {
System.out.println("五菱宏光");
}
}
public class WuLingFactory implements CarFactory{
@Override
public Car getCar(){
return new WuLing();
}
}