/** * @Project: spring * @description: 实现车子的接口 * @author: sunkang * @create: 2018-08-29 23:06 * @ModificationHistory who when What **/ publicinterfaceCar { String getName(); }
有三个具体的实现类
/** * @Project: spring * @description: 奥迪车 * @author: sunkang * @create: 2018-08-29 23:07 * @ModificationHistory who when What **/ publicclassAudiimplementsCar { @Override public String getName() { return"audi"; } }
/** * @Project: spring * @description:奔驰车 * @author: sunkang * @create: 2018-08-29 23:08 * @ModificationHistory who when What **/ publicclassBenzimplementsCar { @Override public String getName() { return"benz"; } }
/** * @Project: spring * @description: 宝马车 * @author: sunkang * @create: 2018-08-29 23:08 * @ModificationHistory who when What **/ publicclassBmwimplementsCar { @Override public String getName() { return"bmw"; } }
简单工厂的方法:
/** * @Project: spring * @description: 简单工厂 根据传入不同的参数得到不同对象 * @author: sunkang * @create: 2018-08-29 23:10 * @ModificationHistory who when What **/ publicclassSimpleFactory { public Car getCar(String name){ if("BMW".equalsIgnoreCase(name)){ returnnewBmw(); }elseif("Benz".equalsIgnoreCase(name)){ returnnewBenz(); }elseif("Audi".equalsIgnoreCase(name)){ returnnewAudi(); }else{ System.out.println("这个产品产不出来"); returnnull; } } }
工厂方法模式(Factory Method)
/** * @Project: spring * @description: 造车工厂的接口 * @author: sunkang * @create: 2018-08-30 22:33 * @ModificationHistory who when What **/ publicinterfaceFactory { Car getCar(); }
/** *生产奥迪的工厂 */ publicclassAudiFactoryimplementsFactory { @Override public Car getCar() { returnnewAudi(); } }
/** *生产奔驰的工厂 */ publicclassBenzFactoryimplementsFactory { @Override public Car getCar() { returnnewBenz(); } }
/** * 生产宝马的工厂 */ publicclassBmwFactoryimplementsFactory { @Override public Car getCar() { returnnewBmw(); } }
publicabstractclassAbstractFactory { /** * 得到奥迪的车 * @return */ publicabstract Car getAudiCar(); /** * 得到奔驰的车 * @return */ publicabstract Car getBenzCar(); /** * 得到宝马的车 * @return */ publicabstract Car getBmwCar(); }
抽象工厂的具体实现
/** * @Project: spring * @description: 抽象工厂的具体实现 * @author: sunkang * @create: 2018-09-01 19:37 * @ModificationHistory who when What **/ publicclassCarFactoryextendsAbstractFactory { @Override public Car getAudiCar() { returnnewAudi(); } @Override public Car getBenzCar() { returnnewBenz(); } @Override public Car getBmwCar() { returnnewBmw(); } }