search
HomeJavajavaTutorialDetailed explanation of the creator pattern of design patterns

Definition (From Baidu Encyclopedia):
The core idea is to separate a "complex object construction algorithm" from its "components and assembly methods", so that the component algorithms and assembly methods can Respond to changes independently;
Reusing the same construction algorithm can create different representations, and different construction processes can reuse the same component assembly method

UML Class Diagram:

##Specific code:

public class Client {public static void main(String[] args) {
        Director d = new Director(new ConcreteBuilder());
        d.construct();
    }
}public class Director {
    Builder builder;

    Director(Builder builder){this.builder = builder;
    }void construct(){
        builder.buildPart();
    }
}public class ConcreteBuilder implements Builder {private Product product;public Product getResult() {return product;
    }

    @Overridepublic void buildPart() {

    }
}public class Product {

}

For example:

A car is composed of many parts, ranging from the engine to the rearview mirror. It is obviously unrealistic to assemble a car and give it to the user. After all, what the user wants is just a He doesn't care how you build a car.

For example, if I want an Audi, then when it comes to the above example, I will tell the Director that I want to construct an Audi.
Then Director finds the Builder interface (ConcreteBuilder instance) corresponding to Audi. ConcreteBuilder knows the various parts and steps of building Audi.
For example, first build a big frame, then choose an engine, then choose a suitable tire, and finally press A rearview mirror, these steps are the process of buildPart. In short, it is a very complicated process,
but for users, it is Audi and does not care about these complicated processes.
Also, this example seems to be very similar to the abstract factory, but there is an important difference. The factory is only responsible for producing the various parts of the car and is not responsible for assembling it.
This is an important part to distinguish between the two modes.

Composition of various parts:

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.

Corresponding to the above example is the assembly of various parts of the car, such as the frame, engine, etc.

ConcreteBuilder: Implements the Builder interface to concretely create each part of a complex object for different business logic. After the building process is complete, provide examples of the product.
Corresponding to the above is to assemble the Audi Builder, and add the wheels of the agricultural machinery step by step...
Director: Call specific builders to create various parts of complex objects. The director does not involve specific product information. It is only responsible for ensuring that all parts of the object are created completely or in a certain order.
The word "Director" means director, and his responsibility is also very clear: scheduling. In the above example, if my idea as a producer is to use Audi, the director will notify ConcreteBuilder to do it.
Product: The complex object to be created.
The one corresponding to the above is Audi.

Advantages and Disadvantages:

Advantages: Loose coupling: Breaking down the creation steps of complex products into different methods makes the creation process clearer and enables us to be more precise to control the generation process of complex objects.
Better reusability: Building products and assembling and disassembling make building products reusable.

Disadvantages:
The products created by the builder mode generally have many things in common and their components are similar. If the differences between the products are large, the builder mode is not suitable, so Its scope of use is subject to certain restrictions.
If the internal changes of the product are complex, it may be necessary to define many specific builder classes to implement such changes, causing the system to become very large.

refer to:

The above is the detailed content of Detailed explanation of the creator pattern of design patterns. 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
Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

How do Java's Top Features Impact Performance and Scalability?How do Java's Top Features Impact Performance and Scalability?May 12, 2025 am 12:08 AM

Java'stopfeaturessignificantlyenhanceitsperformanceandscalability.1)Object-orientedprincipleslikepolymorphismenableflexibleandscalablecode.2)Garbagecollectionautomatesmemorymanagementbutcancauselatencyissues.3)TheJITcompilerboostsexecutionspeedafteri

JVM Internals: Diving Deep into the Java Virtual MachineJVM Internals: Diving Deep into the Java Virtual MachineMay 12, 2025 am 12:07 AM

The core components of the JVM include ClassLoader, RuntimeDataArea and ExecutionEngine. 1) ClassLoader is responsible for loading, linking and initializing classes and interfaces. 2) RuntimeDataArea contains MethodArea, Heap, Stack, PCRegister and NativeMethodStacks. 3) ExecutionEngine is composed of Interpreter, JITCompiler and GarbageCollector, responsible for the execution and optimization of bytecode.

What are the features that make Java safe and secure?What are the features that make Java safe and secure?May 11, 2025 am 12:07 AM

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

Must-Know Java Features: Enhance Your Coding SkillsMust-Know Java Features: Enhance Your Coding SkillsMay 11, 2025 am 12:07 AM

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)Object-orientedprogrammingallowsmodelingreal-worldentities,exemplifiedbypolymorphism.2)Exceptionhandlingprovidesrobusterrormanagement.3)Lambdaexpressionssimplifyoperations,improvingcodereadability

JVM the most complete guideJVM the most complete guideMay 11, 2025 am 12:06 AM

TheJVMisacrucialcomponentthatrunsJavacodebytranslatingitintomachine-specificinstructions,impactingperformance,security,andportability.1)TheClassLoaderloads,links,andinitializesclasses.2)TheExecutionEngineexecutesbytecodeintomachineinstructions.3)Memo

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

mPDF

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.