Factory design pattern: In order to understand the coupling to separate the user who created the object object.
Life: in series production
in Java: mass-produced objects
Division:
their production (create) objects and using objects separated, decoupling
1, a simple factory pattern
advantage: the code is relatively simple
Cons: If you add a new product type, you need to modify the factory class
in violation of an object-oriented development principles: open for extension, but closed for modification
2, the factory method pattern
(1) In order to separate the production and use of target objects
(2) if the increase in new products, there is no need to modify the original factory class
advantages: Following the addition of new products, without modifying the principle of the original class,
Cons: too much class
Example: simple factory pattern
class SimpleFactory2{
public static Car getCar(String type){
if("BMW".equals(type)){
return new BMW();
}else if("BZ".equals(type)){
return new Benz();
}
return null;
}
}
Example: Factory Method
interface Factory{
VehiCle getVehiCle ();
}
class BMWFactory implements Factory{
@Override
public Che getChe() {
return new BaoMa();
}
}
class BZFactory implements Factory{
@Override
public Che getChe() {
return new BZ();
}
}
......
Example: Using reflection, in combination with simple plant factory method model pattern
class SimpleFactory{
public static Vehicle getVehicle(String className)throws Exception{
Class clazz = Class.forName(className);
Object obj = clazz.newInstance();
if(obj instance of Vehicle){
return (Vehicle) obj;
}
return null;
}
}