1. What is builder mode?
We know that in the software development process, sometimes we need to create a very complex object, which is usually composed of multiple sub-components according to certain steps.
For example, when we assemble a computer ourselves, we need to assemble it from CPU, motherboard, memory, hard disk, graphics card, chassis, monitor, keyboard, mouse and other components. For example, if a school needs to purchase 100 computers, it is impossible for the school to buy the parts and assemble them by itself. It must tell the buyer what configuration it needs, and then the buyer will go to the computer company to buy them. The company will assemble them for you and then hand them over to the buyer. , and finally handed it over to the school.
As can be seen from the above example, each component can be flexibly selected (including the level of various computer configurations), but the creation steps are similar. However, the creation of this type of product cannot be described by the factory pattern introduced earlier. Only the builder pattern can well describe the creation of this type of product.
2. Definition of Builder Pattern
Definition of Builder Pattern:
Separates the construction of a complex object from its representation so that the same construction process can create Differently represented, such a design pattern is called the builder pattern. It breaks down a complex object into multiple simple objects and then builds it step by step. It separates change from immutability, that is, the components of the product remain unchanged, but each part can be flexibly selected.
Summary in one sentence: Separate the construction of a complex object from its representation, so that the same construction process can create different representations
Type: Create a class pattern
3. Advantages and Disadvantages of Builder Pattern
Advantages:
Good encapsulation, separation of construction and presentation
Extensibility Better, each specific builder is independent of each other, which is conducive to system decoupling
The client does not need to know the details of the internal composition of the product, the builder can gradually refine the creation process, Without having any impact on other modules, it is easy to control detailed risks
Disadvantages:
The components of the product must be the same, which limits its use Scope
If the internal changes of the product are complex, if the internal changes of the product occur, the builder will also have to make simultaneous modifications, and the later maintenance cost will be larger
Note:
The builder pattern and the factory pattern have different focuses: the builder pattern focuses on the assembly process of components, while the factory method pattern focuses more on the creation process of components, but the two can be used in combination.
4. The structure of the builder pattern
The main roles of the builder pattern are as follows:
Product role (Product): It contains multiple Complex objects that make up components, each component is created by a specific builder
Abstract Builder (Builder): Implements the Builder interface to construct and assemble the various components of the product, defined And clarify the representation it creates, and provide an interface for retrieving products
Concrete Builder: Construct an object using the Builder interface to guide the construction process
Director: It calls the component construction and assembly methods in the builder object to complete the creation of complex objects. The director does not involve specific product information
Structural diagram (referenced from the Internet):
5. Builder mode code demonstration
For example, now we need to build a car:
Product category:
/** * 产品类 */ public class Car { //车的建造过程 private String wheel; //车轮 private String skeleton; //车架 private String engine; //发动机 public String getWheel() { return wheel; } public void setWheel(String wheel) { this.wheel = wheel; } public String getSkeleton() { return skeleton; } public void setSkeleton(String skeleton) { this.skeleton = skeleton; } public String getEngine() { return engine; } public void setEngine(String engine) { this.engine = engine; } }
Instructor category:
/** * 指导者 */ //汽车总监 public class CarDirector { public Car constructCar(ICarBuilder builder){ builder.buildwheel(); builder.buildSkeleton(); builder.buildEngine(); return builder.buildCar(); } }
Concrete builder:
/** * 具体建造者:生产具体的东西 */ public class ConcreteBuilder implements ICarBuilder{ Car car; public ConcreteBuilder(){ car = new Car(); } @Override public void buildwheel() { car.setWheel("轮子"); } @Override public void buildSkeleton() { car.setSkeleton("车身结构"); } @Override public void buildEngine() { car.setEngine("发动机"); } @Override public Car buildCar() { return this.car; } }
Abstract builder (interface):
/** * 抽象建造者 */ public interface ICarBuilder { public void buildwheel(); //构建车轮 public void buildSkeleton(); //构建骨架 public void buildEngine(); //构建发动机 Car buildCar(); }
Test category:
public class Test { public static void main(String[] args){ //新建一个总监(替你去买汽车) CarDirector director = new CarDirector(); Car car = director.constructCar(new ConcreteBuilder()); System.out.println(car.getWheel()); System.out.println(car.getEngine()); System.out.println(car.getSkeleton()); } }
After reading the code demonstration and combining it with the first part of the article, you can understand it! !
6. Application scenarios of the builder pattern
The only difference between the builder pattern and the factory pattern is the creation of complex objects. In other words, if you create simple objects, you usually use the factory pattern to create them, and if you create complex objects, you can consider using the builder pattern
Main application scenarios:
-
The same method, different execution order, produces different results
Multiple components or parts can be assembled into one object, but the results produced are different
The product class is very complex, or different calling sequences in the product class produce different effects
Initializing an object is particularly complex, with many parameters, and Many parameters have default values
7. The difference between builder mode and factory mode
Builder mode pays more attention to the calling order of methods. The factory pattern focuses on creating objects
-
The intensity of creating objects is different. The builder pattern creates complex objects, which are composed of various complex components. The objects created by the factory pattern are all the same
The focus is different. The factory mode only needs to create the object, while the builder mode not only needs to create the object, but also knows what parts the object is composed of
The builder mode is different according to the order in the construction process, and the final object component composition is also different
The above is the detailed content of What is the builder pattern in Java design patterns?. For more information, please follow other related articles on the PHP Chinese website!

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages such as Python and JavaScript to enhance cross-language interoperability.

Java's strong typed system ensures platform independence through type safety, unified type conversion and polymorphism. 1) Type safety performs type checking at compile time to avoid runtime errors; 2) Unified type conversion rules are consistent across all platforms; 3) Polymorphism and interface mechanisms make the code behave consistently on different platforms.

JNI will destroy Java's platform independence. 1) JNI requires local libraries for a specific platform, 2) local code needs to be compiled and linked on the target platform, 3) Different versions of the operating system or JVM may require different local library versions, 4) local code may introduce security vulnerabilities or cause program crashes.

Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages for performance.

Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version
SublimeText3 Linux latest version
