What is the builder mode: If the definition on the Internet is relatively not easy to understand, we can make an analogy, when we need to build a complex object, for example, to build a car, then we need to make the various components of the car, such as wheels, engines, steering wheel, rearview mirror, etc. The components are then assembled and eventually assembled into a complete vehicle. the essence of the builder model is to separate the production of the components from the final assembly. This makes the code more modular and easier to maintain.
Example Builder mode:
1 Define a builder (build) interface, declaring "the method of producing each part and the method of assembling each part";
public interface Builder
{
public void Builderparta () {}//production a part
public void Builderpartb () {}//production B parts
public void Builderpartc () {}//production C parts
Public Product GetResult () {}//Assemble individual parts
}
2 Define a class, implement the interface, add specific methods to produce each part and assemble the various parts of the method
public class Createbuilder implements Builder
{
public void Builderparta () {.............} Production of Part A
public void Builderpartb () {.............} Production of B parts
public void Builderpartc () {............. ...} Production of C components
Public Product GetResult () {...........} Assemble individual Parts
}
3 Define a class Derictor: a product specifically designed for users to send production component commands and obtain final assembly
To use the Createbuilder method in this class , you need to declare the Createbuilder object in the Derictor
public class Derictor
{
Private Createbuilder builder;
Public Derictor ( createbuilder builder)
{
This. builder=Builder;
}
Production of individual components
public void Constructparts ()
{
Builder. Builderparta ();
Builder. BUILDERPARTB ();
Builder. BUILDERPARTC ();
}
Assemble the final product
Public Product Constructresult ()
{
Builder. GetResult ();
}
}
4 Calls:
Createbuilder mbuilder=new Createbuilder ();
Derictor mderictor=new derictor (mbuilder);
m Derictor. constructparts ();
product mproduct=derictor. constructresult ();
Finally build complex objects mproduct
If the objects we build are more complex, then we will consider using the builder model to separate the production and assembly of the parts, giving the user only the means to produce the parts and assemble the parts, how to produce them, and how to assemble the matter.
Design mode--builder mode