Design mode
preface
1, Builder model
1. Definitions
Separate the construction of a complex object from its representation, so that the same construction process can create different representations
2. Main functions
When users do not know the construction process and details of objects, they can directly create complex objects.
- Users only need to specify the type and content of complex objects;
- The builder pattern is responsible for creating complex objects in sequence (hiding the internal construction process and details)
3. Problems solved
- Convenient for users to create complex objects (no need to know the implementation process)
- Code reusability & encapsulation (encapsulating & reusing the object construction process and details)
Example: making cars & Buy a car. Factory (builder mode): responsible for manufacturing cars (assembly process and details are in the factory) Car buyer (user): you just need to say the model you need (object type and content), and then buy it directly (You don't need to know how the car is assembled (wheels, doors, engine, steering wheel, etc.)
Example: pandas is a NumPy based tool created to solve data analysis tasks.
Two, mode principle
1. Mode explanation
- The Director directly communicates with the Client on the demand;
- After communication, the commander divides the customer's demand for creating products into the construction request (Builder) of each component;
- Delegate the construction request of each component to a specific builder;
- Each specific builder is responsible for the construction of product parts;
- Finally, it is built into a specific Product.
2. Example explanation
2.1 example overview
Background: Xiaocheng hopes to go to the computer city to buy an assembled desktop host
Process:
1. The computer city owner (Diretor) and Xiaocheng (Client) communicate their needs (buy to play games, study, watch movies?)
2. After understanding the requirements, the boss of the computer city divides the host required by Xiaocheng into the construction requests (CPU and motherboard BLA) of each component (Builder)
Command the installation personnel (ConcreteBuilder) to build components;
A computer (Product) needed to assemble components into a small assembly
2.2 use steps
Step 1: define the assembly process (Builder): the process of assembling the computer
public abstract class Builder { //Step 1: install CPU //Declared as an abstract method, which is implemented by subclasses public abstract void BuildCPU(); //Step 2: install the motherboard //Declared as an abstract method, which is implemented by subclasses public abstract void BuildMainboard(); //Step 3: install the hard disk //Declared as an abstract method, which is implemented by subclasses public abstract void BuildHD(); //How to return the product: get the assembled computer public abstract Computer GetComputer(); }
Step 2: the boss of the computer city assigns tasks to the installation Director
public class Director{ //Command the installation personnel to assemble the computer public void Construct(Builder builder){ builder. BuildCPU(); builder.BuildMainboard(); builder. BuildHD(); } }
Step 3: create concrete Builder: installation personnel
//Installation personnel 1 public class ConcreteBuilder extend Builder{ //Create a product instance Computer computer = new Computer(); //Assembled products @Override public void BuildCPU(){ computer.Add("assemble CPU") } @Override public void BuildMainboard(){ computer.Add("Assemble the motherboard") } @Override public void BuildHD(){ computer.Add("Assemble the motherboard") } //Return the computer successfully assembled @Override public Computer GetComputer(){ return computer } }
Step 4: define a specific Product category: computer
public class Computer{ //Collection of computer components private List<String> parts = new ArrayList<String>(); //Used to assemble components into a computer public void Add(String part){ parts.add(part); } public void Show(){ for (int i = 0;i<parts.size();i++){ System.out.println(""Component"+parts.get(i)+""It's ready"); } System.out.println("The computer is assembled, please accept "); } }
Step 5: client call - Xiaocheng goes to the computer city to find the boss to buy a computer
public class Builder Pattern{ public static void main(String[] args){ //After wandering for a long time, I finally found a suitable computer store //Find the owner and installer of the store Director director = new Director(); Builder builder = new ConcreteBuilder(); //After communicating the demand, the boss asked the installer to install the computer director.Construct(builder); //After installation, the assembly personnel moved to the assembled computer Computer computer = builder.GetComputer(); //The assembler showed the computer to Xiao Cheng computer.Show(); } }
assembly CUP It's ready The component motherboard is installed The component hard disk is installed The computer is assembled, please check and accept
3, Advantages and disadvantages
1. Advantages
- Easy decoupling
By decoupling the product itself from the product creation process, you can use the same creation process to get different products. That is to say, details depend on abstraction. - It is easy to precisely control the creation of objects
The creation steps of complex products are decomposed into different methods to make the creation process clearer - Easy to expand
Adding new specific builders does not need to modify the code of the original class library, which is easy to expand and in line with the "opening and closing principle".
Each specific builder is relatively independent and has nothing to do with other specific builders. Therefore, it is convenient to replace or add new specific builders. Users can get different product objects by using different specific builders.
2. Disadvantages
-The products created by the builder model generally have more in common, and their components are similar; If there are great differences between products, it is not suitable to use the builder mode, so its scope of use is limited.
- If the internal changes of the product are complex, it may lead to the need to define many specific builder classes to realize this change, resulting in a huge system.
4, Application scenario
- The product objects to be generated have complex internal structures, and these product objects have commonalities;
- Isolate the creation and use of complex objects and enable the same creation process to create different products.
5, Application in MyBatis
The most classic builder mode in MyBatis must be the process of obtaining SqlSessionFactory.
The following is a typical usage of getting SqlSessionFactory.
CopyClassPathResource resource = new ClassPathResource("mybatis-config.xml"); InputStream inputStream = resource.getInputStream(); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
It is found from the above code that the code for creating SqlSessionFactory is in SqlSessionFactoryBuilder. Go in and find out:
//The whole process is to parse the configuration file into a configuration object, and then create SqlSessionFactory //Configuration is an internal property of SqlSessionFactory public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) { try { XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties); return build(parser.parse()); } catch (Exception e) { throw ExceptionFactory.wrapException("Error building SqlSession.", e); } finally { ErrorContext.instance().reset(); try { inputStream.close(); } catch (IOException e) { // Intentionally ignore. Prefer previous error. } } } public SqlSessionFactory build(Configuration config) { return new DefaultSqlSessionFactory(config); }
The code is relatively simple, so there is no specific analysis. Here is the right seat. List the roles.
- SqlSessionFactoryBuilder: conductor role
- BaseBuilder: Abstract Builder
- XMLConfigBuilder: specific Builder
- SqlSessionFactory: the product to be created
Reference documents
Programmer Freedom Road
Builder Pattern - the most understandable design pattern analysis