This article mainly introduces the usage of Builder. Share it with everyone for your reference. The details are as follows:
I was looking at the source code of Mybatis
recently, and in the process of reading and parsing the XML
configuration file, I found that the builder mode was used. Therefore, I plan to review this design pattern.
Origin
Suppose we need to draw a little person, we may have the following constructor definition:
public Person(HeadType headType, HairType hairType, HairColor hairColor, FaceType faceType, BodyType bodyType, ArmType amrType, LegType legTyype) { }
Seeing such a constructor, we estimate that we will come back later I was confused when I saw it. There are so many parameters, which makes subsequent maintenance very troublesome for us.
The construction pattern can solve such problems.
Use
The goal is to draw a little person
1. Define the abstract Builder
First define the abstract PersonBuilder
. This class defines the steps required to draw a villain, so that each object generated through PersonBuilder
is essentially the same, but can have different personalities.
abstract class PersonBuilder { protected Graphics graphics; public PersonBuilder(Graphics graphics) { this.graphics = graphics; } public abstract void buildHead(); public abstract void buildBody(); public abstract void buildArmLeft(); public abstract void buildArmRight(); public abstract void buildLegLeft(); public abstract void buildLegRight(); }
2. Define a specific Builder
class
and define a specific implementation class PersonFatBuilder
. This class inherits PersonBuilder
and implements abstract methods.
3. Define the specific Director
class
This class is responsible for the specific construction process and does not care about what is built.
public class PersonDirector { private PersonBuilder personBuilder; public PersonDirector(PersonBuilder personBuilder) { this.personBuilder = personBuilder; } public void drawPerson() { personBuilder.buildHead(); personBuilder.buildBody(); personBuilder.buildArmLeft(); personBuilder.buildArmRight(); personBuilder.buildLegLeft(); personBuilder.buildLegRight(); } }
4. Test
Create a window and draw the villain.
public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { // 创建窗口对象 JFrame frame = new JFrame(); frame.setVisible(true); frame.setTitle("画人"); frame.setSize(250, 300); // 设置窗口关闭按钮的默认操作(点击关闭时退出进程) frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // 把窗口位置设置到屏幕的中心 frame.setLocationRelativeTo(null); frame.setContentPane(new JPanel(){ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); PersonThinBuilder thinBuilder = new PersonThinBuilder(g); PersonDirector director = new PersonDirector(thinBuilder); director.drawPerson(); } }); } }); }
The results are as follows:
Definition
Literal definition
Compare the construction of complex objects with it Separation of representations allows the same construction process to create different representations.
In other words, it allows you to create different types of objects while avoiding pollution of the constructor. This pattern is useful when there are multiple types of objects. Or there are many steps involved in creating an object.
Structural diagram
Quoting a diagram from "Dahua Design Pattern"
Builder: Create
ProductObject and abstract interface.
ConcreateBuilder: Specific builder, constructs and assembles various components.
Product: The object we need to build.
Director: Used to create products, it has member variables of type
Builder inside.
- ##Director
No need to know the internal details of
Product
, it only provides the required information to the builder, It is processed by the specific builderConcreateBuilder
to complete the construction of the product. The builder pattern disperses the complex product creation process into different objects, thereby achieving more precise control over the product creation process and making the creation process clearer. - Each specific builder can create a complete product object, and it is independent of each other. Therefore, the caller can get different objects through different concrete builders. When a new product appears, there is no need to change the original code, just add a builder.
- Example
Now if we want to build a fat little man with facial features. Then we only need to add a
PersonFatBuilder class, and there is no need to change the original code. <pre class='brush:php;toolbar:false;'>public class PersonFatBuilder extends PersonBuilder {
public PersonFatBuilder(Graphics graphics) {
super(graphics);
}
@Override
public void buildHead() {
graphics.drawOval(50, 20, 30, 30);
graphics.drawArc(50, 30, 10, 5, 45, 135);
graphics.drawArc(70, 30, 10, 5, 45, 135);
graphics.drawArc(60, 35, 10, 5, 200, 135);
}
@Override
public void buildBody() {
graphics.drawRect(55, 50, 20, 50);
}
@Override
public void buildArmLeft() {
graphics.drawLine(55, 50, 40, 100);
}
@Override
public void buildArmRight() {
graphics.drawLine(75, 50, 90, 100);
}
@Override
public void buildLegLeft() {
graphics.drawLine(55, 100, 45, 150);
}
@Override
public void buildLegRight() {
graphics.drawLine(75, 100, 85, 150);
}
}</pre>
Result:
Related recommendations:
The above is the detailed content of Java design patterns-Builder pattern. For more information, please follow other related articles on the PHP Chinese website!

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

Java requires specific configuration and tuning on different platforms. 1) Adjust JVM parameters, such as -Xms and -Xmx to set the heap size. 2) Choose the appropriate garbage collection strategy, such as ParallelGC or G1GC. 3) Configure the Native library to adapt to different platforms. These measures can enable Java applications to perform best in various environments.

OSGi,ApacheCommonsLang,JNA,andJVMoptionsareeffectiveforhandlingplatform-specificchallengesinJava.1)OSGimanagesdependenciesandisolatescomponents.2)ApacheCommonsLangprovidesutilityfunctions.3)JNAallowscallingnativecode.4)JVMoptionstweakapplicationbehav

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.


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.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

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