2.0 - The Three Musketeers design patterns factory pattern - factory method pattern

2.0 design patterns factory method pattern

Factory Method pattern (Fatory Method Pattern) refers to the definition of a created object's interface, but let's implement this interface to decide which instance of the class factory method to instantiate the class allow deferred to subclasses were. In the Factory Method pattern in users only need to be concerned about the desired product corresponding to the plant, without concern for the details of creating and adding new products in line with the principle of opening and closing. Factory method pattern to solve the main problem of product extensions, in a simple factory, with the rich product chain, if you create a logical course of each are different, then the responsibility will become more and more factories, a bit like a universal plant, and not easy to maintain. According to the principle of single responsibility we will continue to split the functions, specializing in hand dry. Cadillac created by CadillacFactory factory, Audi created by AudiFactory factory, the factory also made itself an abstract. Look at the code,

/**
 * 工厂接口
 */
public interface ICarFactory {
    ICar create();
}
/**
 * 生产奥迪车的工厂
 */
public class AudiFactory implements ICarFactory {
    @Override
    public ICar create() {
        return new AudiCar();
    }
}
/**
 * 生产凯迪拉克的工厂
 */
public class CadillacFactory  implements ICarFactory{
    @Override
    public ICar create() {
        return new CadillacCar();
    }
}

The client calls

/**
 * 工厂方法测试类
 * 优点:符合开闭原则,降低了客户端和工厂的耦合性
 * 缺点:每增加一个产品,就增加一个工厂
 */
public class FactoryTest {

    public static void main(String[] args) {
        ICarFactory AudiFactory=new AudiFactory();
        AudiFactory.create().run();

        ICarFactory cadillacFactory=new CadillacFactory();
        cadillacFactory.create().run();
    }

}

Consider the following class diagram:

 Look at the factory method in the application pattern logback see FIG class on OK:

 Factory method applies to the following scenarios:

1, to create an object requires a lot of repetitive code.

2, the client (application layer) does not depend on how the product class instance is created, the details of realization.

3, a class to specify which object created by its subclasses.

Factory method has its drawbacks:

1, the number of class too readily, increasing the complexity.

2, increasing the system's abstract and difficult to understand.

Guess you like

Origin blog.csdn.net/madongyu1259892936/article/details/93748031