search
HomeJavajavaTutorialJava design patterns-Builder pattern

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.

<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>

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:

Java design patterns-Builder pattern

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"

Java design patterns-Builder pattern

##Abstract class

Builder: Create ProductObject and abstract interface.

Inherited class

ConcreateBuilder: Specific builder, constructs and assembles various components.

Specific product category

Product: The object we need to build.

Director: Used to create products, it has member variables of type Builder inside.

Advantages

  1. ##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 builder ConcreateBuilder to complete the construction of the product.

  2. 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.
  3. 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.
  4. 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:

Java design patterns-Builder patternRelated recommendations:


[oracle tutorial]Starting with Oracle Warehouse Builder 11g Rel

yii Query Builder (yii Query Builder) Official Guide Translation

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java数据结构之AVL树详解Java数据结构之AVL树详解Jun 01, 2022 am 11:39 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

一文掌握Java8新特性Stream流的概念和使用一文掌握Java8新特性Stream流的概念和使用Jun 23, 2022 pm 12:03 PM

本篇文章给大家带来了关于Java的相关知识,其中主要整理了Stream流的概念和使用的相关问题,包括了Stream流的概念、Stream流的获取、Stream流的常用方法等等内容,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft