Simple Factory model
define
The factory pattern can be divided into simple factory pattern, factory method pattern, and abstract factory pattern. We call the objects we create products, and the objects we create products are called factories. If we create a few products, we only need one factory
The advantages and disadvantages
- Advantages:
- The factory class contains the logical judgment necessary to determine which instance of a product to create and when. The client can be relieved of the responsibility of creating product objects directly, making it easy to create corresponding products. The responsibilities of plant and product are clearly differentiated.
- The client does not need to know the class name of the specific product being created, just the parameters.
- Configuration files can also be introduced to replace and add new concrete product classes without modifying the client code.
- Disadvantages:
- Factory type is single, responsible for the creation of all products, excessive responsibilities, violating the principle of high cohesion
- Scaling is difficult, and the factory logic needs to be modified as soon as new product requirements are added
- The simple factory pattern uses the static factory method and therefore cannot be inherited
Application scenarios
In the case of a small variety of products, the client only needs to pass in the parameters required by the factory class, regardless of how to createCopy the code
Structure and implementation of patterns
structure
+ Simple factory: is the core of this pattern, responsible for creating all instances of the logic, can be directly called by the outside world, create products + abstract products: is the parent of all products, responsible for describing all instances of the public interface + concrete products:Copy the code
The specific implementation
example
/** * public interface Product{void show(); Static class ConcreteProduct1 implements Product{@override public void show(){} System.out.println(" show method for specific product 1 "); Static class ConcreteProduct2 implements Product{@override public void show(){} System.out.println(" show method for specific product 2 "); Static class SimpleFactory{public static Product makeProduct(int number){switch (number){case 1: return new ConcreteProduct1(); case 2: return new ConcreteProduct2(); default: break; } return null; }}Copy the code
Copy the code