publicclassSimpleCarFactory{publicstaticCarcreateCar(CarTypetype){if(type==null){thrownewIllegalArgumentException("type cannot be null");}if(type==CarType.BMW){returnnewBmwCar();}elseif(type==CarType.VOLVO){returnnewVolvoCar();}elseif(type==CarType.TESLA){returnnewTeslaCar();}else{thrownewIllegalArgumentException("Unknown car type: "+type);}}}
另外,SimpleCarFactory 这个工厂类因为需要包含所有 Car 的生产逻辑,它必须依赖所有的类型。这导致客户端代码耦合所有的可选产品类型,而这些产品类型的依赖调用端可能永远也不需要使用。假设我们将各种具体产品类型和它们相关的实现类分别打包成为独立模块,则这个超级工厂需要依赖所有的模块。而我们希望的是,当我们生产某种特定的产品类型时,提供相应的实现的模块依赖即可。
publicstaticclassCarFactoryWithReflection{privateMap<CarType,Class<?extendsCar>>registeredCarTypes=newConcurrentHashMap<>();privatestaticCarFactoryWithReflectionINSTANCE;privateCarFactoryWithReflection(){}publicstaticCarFactoryWithReflectioninstance(){if(INSTANCE==null){INSTANCE=newCarFactoryWithReflection();}returnINSTANCE;}publicvoidregisterCar(CarTypetype,Class<?extendsCar>carClass){this.registeredCarTypes.put(type,carClass);}publicCarcreateCar(CarTypetype){if(type==null){thrownewIllegalArgumentException("type cannot be null");}Class<?extendsCar>carClass=registeredCarTypes.get(type);if(carClass==null){thrownewRuntimeException("Car type not registered: "+type);}try{Constructor<?extendsCar>carConstructor=carClass.getDeclaredConstructor();returncarConstructor.newInstance();}catch(Exceptione){thrownewRuntimeException("Car of type "+type+" cannot be instantiated",e);}}}
publicstaticclassCarFactoryWithoutReflection{privateMap<CarType,Car>registeredCars=newConcurrentHashMap<>();privatestaticCarFactoryWithoutReflectionINSTANCE;privateCarFactoryWithoutReflection(){}publicstaticCarFactoryWithoutReflectioninstance(){if(INSTANCE==null){INSTANCE=newCarFactoryWithoutReflection();}returnINSTANCE;}publicvoidregisterCar(CarTypetype,Carcar){this.registeredCars.put(type,car);}publicCarcreateCar(CarTypetype){if(type==null){thrownewIllegalArgumentException("type cannot be null");}Carcar=registeredCars.get(type);if(car==null){thrownewRuntimeException("Car type not registered: "+type);}returncar.create();}// make sure car type is registered to the factory before creating cars
static{try{Class.forName("me.donggan.patterns.factory.simple.model.BmwCar");Class.forName("me.donggan.patterns.factory.simple.model.VolvoCar");Class.forName("me.donggan.patterns.factory.simple.model.TeslaCar");}catch(ClassNotFoundExceptioncnfe){cnfe.printStackTrace();}}publicstaticvoidmain(String[]args){Carcar1=CarFactoryWithoutReflection.instance().createCar(CarType.BMW);car1.drive();Carcar2=CarFactoryWithoutReflection.instance().createCar(CarType.VOLVO);car2.drive();Carcar3=CarFactoryWithoutReflection.instance().createCar(CarType.TESLA);car3.drive();}}