search
HomeJavajavaTutorialWhat is Java Builder Pattern? How to achieve? (with code)

This article brings you what is the Java builder pattern? How to achieve? (Attached is the code), which has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Builder Mode

1. What is Builder Mode?

 Builder Pattern uses multiple simple objects to build a complex object step by step.
A Builder class will construct the final object step by step. This Builder class is independent of other objects.
The builder pattern is mainly used in software systems. Sometimes we are faced with the creation of "a complex object", which is usually composed of sub-objects of each part using a certain algorithm; Due to changes in requirements, this complex object The individual parts of an object often face drastic changes, but the algorithms that put them together are relatively stable.

2. Specific implementation of builder mode

Structural diagram

What is Java Builder Pattern? How to achieve? (with code)

Four roles in builder mode:
  1. Builder: Provides an abstract interface to standardize the construction of each component of the product object. This interface specifies which parts of the complex object are to be created, and does not involve the creation of specific object components.

  2. ConcreteBuilder: Implements the Builder interface to concretize the creation of each part of a complex object for different business logic. After the building process is complete, provide examples of the product.

  3. Director: Call specific builders to create various parts of complex objects. The director does not involve specific product information, but is only responsible for ensuring that all parts of the object are completely created or in a certain order. create.

  4. Product: The complex object to be created.

java code implementation

1. Create human entity class

package com.designpattern.builderPattern;

/**
 * 对象 人
 *
 * @author zhongtao on 2018/9/17
 */
public class Human {

    private String head;
    private String body;
    private String hand;
    private String foot;

    public String getHead() {
        return head;
    }

    public void setHead(String head) {
        this.head = head;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public String getHand() {
        return hand;
    }

    public void setHand(String hand) {
        this.hand = hand;
    }

    public String getFoot() {
        return foot;
    }

    public void setFoot(String foot) {
        this.foot = foot;
    }
}

2. Create human Builder interface

package com.designpattern.builderPattern;

/**
 * 造人接口 规定造人的规范 需要头、身体、手、脚
 *
 * @author zhongtao on 2018/9/17
 */
public interface BuilderHuman {

    void buildHead();

    void buildBody();

    void buildHand();

    void buildFoot();

    /**
     * 返回创建的对象
     */
    Human createHuman();

}

3 , ConcreteBuilder creates different types of people

tallPerson

package com.designpattern.builderPattern;

/**
 * 高个子的人
 *
 * @author zhongtao on 2018/9/17
 */
public class TallPersonBuilder implements BuilderHuman {

    Human human;

    public TallPersonBuilder() {
        human = new Human();
    }

    @Override
    public void buildHead() {
        human.setHead("普通的头脑");
    }

    @Override
    public void buildBody() {
        human.setBody("壮实,高大的身体");
    }

    @Override
    public void buildHand() {
        human.setHand("长手");
    }

    @Override
    public void buildFoot() {
        human.setFoot("长脚");
    }

    @Override
    public Human createHuman() {
        return human;
    }
}

smartHuman

package com.designpattern.builderPattern;

/**
 * 聪明的人
 *
 * @author zhongtao on 2018/9/17
 */
public class SmartHumanBuilder implements BuilderHuman {

    Human human;

    public SmartHumanBuilder() {
        human = new Human();
    }

    @Override
    public void buildHead() {
        human.setHead("高智商的头脑");
    }

    @Override
    public void buildBody() {
        human.setBody("健康的身体");
    }

    @Override
    public void buildHand() {
        human.setHand("普通的手");
    }

    @Override
    public void buildFoot() {
        human.setFoot("普通的脚");
    }

    @Override
    public Human createHuman() {
        return human;
    }
}

4. The core of the Director builder pattern calls specific builders to create different people

package com.designpattern.builderPattern;

/**
 * 管理造人的顺序 BuilderHuman不同,则创建的人不同
 * @author zhongtao on 2018/9/17
 */
public class HumanDirector {

    public Human createHumanByDirector(BuilderHuman builderHuman){
        builderHuman.buildHead();
        builderHuman.buildBody();
        builderHuman.buildHand();
        builderHuman.buildFoot();

        return builderHuman.createHuman();
    }
}

5. Builder mode test

package com.designpattern.builderPattern;

import org.junit.Test;

/**
 * 测试
 *
 * @author zhongtao on 2018/9/17
 */
public class BuilderPatternTest {

    /**
     * 测试建造者模式
     */
    @Test
    public void test() {
        HumanDirector humanDirector = new HumanDirector();
        //创建高个子的人
        Human humanByDirector = humanDirector.createHumanByDirector(new TallPersonBuilder());
        System.out.println(humanByDirector.getHead());
        System.out.println(humanByDirector.getBody());
        System.out.println(humanByDirector.getHand());
        System.out.println(humanByDirector.getFoot());

        System.out.println("------简单的分割线------");
        //创建聪明的人
        Human smartHuman = humanDirector.createHumanByDirector(new SmartHumanBuilder());
        System.out.println(smartHuman.getHead());
        System.out.println(smartHuman.getBody());
        System.out.println(smartHuman.getHand());
        System.out.println(smartHuman.getFoot());
    }
}

3. Advantages and disadvantages of builder mode

Advantages:
  1. Builder is independent and easy to expand .

  2. Easy to control detailed risks.

Disadvantages:
  1. Products must have something in common and the scope is limited.

  2. If the internal changes are complex, there will be many construction classes.

Note:

Difference from factory mode, builder mode pays more attention to the order of parts assembly.

The above is the detailed content of What is Java Builder Pattern? How to achieve? (with code). 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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

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尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft