事先准备该链接中的类:
https://www.jianshu.com/p/c5510507cda7
public abstract class AbstractFactory {
protected abstract Car getCar();
public Car getCar(String name){
//这里的是动态配置的功能,具体的业务逻辑交给每个工厂实现类去做
if("BMW".equalsIgnoreCase(name)){
return new BmwFactory().getCar();
}else if("Benz".equalsIgnoreCase(name)){
return new BenzFactory().getCar();
}else if("Audi".equalsIgnoreCase(name)){
return new AudiFactory().getCar();
}else {
System.out.println("这个产品生产不出来");
}
return null;
}
}
//这里是具体业务逻辑的封装
public class AudiFactory extends AbstractFactory {
@Override
public Car getCar() {
//这里可能要调别的接口,查数据库什么的,等等
//很多的业务逻辑
return new Audi();
}
}
//这里是具体业务逻辑的封装
public class BenzFactory extends AbstractFactory {
@Override
public Car getCar() {
//这里可能要调别的接口,查数据库什么的,等等
//很多的业务逻辑
return new Benz();
}
}
//这里是具体业务逻辑的封装
public class BmwFactory extends AbstractFactory {
@Override
public Car getCar() {
//这里可能要调别的接口,查数据库什么的,等等
//很多的业务逻辑
return new Bmw();
}
}
public class DefaultFactory extends AbstractFactory{
private AudiFactory defaultFactory = new AudiFactory();
@Override
protected Car getCar() {
return defaultFactory.getCar();
}
}
public class Test {
public static void main(String[] args) {
//设计模式的经典之处,就在于,解决了编写代码的人和调用代码的人双方的痛楚
//解放双手
DefaultFactory defaultFactory =new DefaultFactory();
System.out.println(defaultFactory.getCar("bmw"));
}
}