第一种简单工厂 点击打开链接
接口Car
public interface ICar {
void carName();
}
public class ACar implements ICar {
@Override
public void carName() {
System.out.println("制造ACar");
}
}
public class BCar implements ICar {
@Override
public void carName() {
System.out.println("制造BCar");
}
}
public class Factory {
public ICar create(String carName){
switch (carName){
case "A":
return new ACar();
case "B":
return new BCar();
default:
return null;
}
}
}
public class Client {
public static void main(String[] args) {
Factory factory = new Factory();
ICar car = factory.create("A");
car.carName();
}
}
三种原则: 面向接口编程 OCP原则 迪米特原则
工厂方法不满足 OCP原则。
第二种:工厂方法