search
HomeBackend DevelopmentGolangBuilder Design Pattern

Builder Design Pattern

The Builder design pattern is used to build complex objects incrementally, allowing the creation of different representations of an object using the same construction process. In this article, we will explore how to implement the Builder pattern in Golang, understand its benefits, and analyze a practical example of use.

What is Builder?

The Builder pattern separates the construction of a complex object from its representation, allowing the same construction process to create different representations. This is especially useful when an object needs to be created in multiple steps or with multiple possible configurations.

Builder Benefits

  • Separation of Construction and Representation: Allows the construction of an object to be separated from its final representation.
  • Incremental Construction: Allows the construction of complex objects incrementally and step by step.
  • Code Reuse: Facilitates code reuse by defining common build steps that can be combined in multiple ways.

Implementing a Builder

To implement our Builder, let's imagine a complex object where it will be necessary to initialize several fields and even other grouped objects. How about a House? Where we will have two types of construction, a conventional one where concrete and bricks will be used, and a second made of wood.

1 - Defining the Structure

First, we need to define the structure of the object we want to build. As said before, we are going to build a house. Inside this Struct we will place what is necessary to create one.

// house.go

package main

type House struct {
    Foundation string
    Structure  string
    Roof       string
    Interior   string
}

2 - Defining the Builder Interface

Still in the same file, we will define the interface of our Builder that specifies the methods necessary to build the different parts of the House.

//house.go

package main

type House struct {
    Foundation string
    Structure  string
    Roof       string
    Interior   string
}

type HouseBuilder interface {
    SetFoundation()
    SetStructure()
    SetRoof()
    SetInterior()
    GetHouse() House
}

3 - Concretely implementing the Builder

Let's create two new files, concreteHouse and woodHouse. They will be the implementation of a concrete class that follows the HouseBuilder interface.

//concreteHouse.go

package main

type ConcreteHouseBuilder struct {
    house House
}

func (b *ConcreteHouseBuilder) SetFoundation() {
    b.house.Foundation = "Concrete, brick, and stone"
}

func (b *ConcreteHouseBuilder) SetStructure() {
    b.house.Structure = "Wood and brick"
}

func (b *ConcreteHouseBuilder) SetRoof() {
    b.house.Roof = "Concrete and reinforced steel"
}

func (b *ConcreteHouseBuilder) SetInterior() {
    b.house.Interior = "Gypsum board, plywood, and paint"
}

func (b *ConcreteHouseBuilder) GetHouse() House {
    return b.house
}
//woodHouse.go

package main

type WoodHouseBuilder struct {
    house House
}

func (b *WoodHouseBuilder) SetFoundation() {
    b.house.Foundation = "Wooden piles"
}

func (b *WoodHouseBuilder) SetStructure() {
    b.house.Structure = "Wooden frame"
}

func (b *WoodHouseBuilder) SetRoof() {
    b.house.Roof = "Wooden shingles"
}

func (b *WoodHouseBuilder) SetInterior() {
    b.house.Interior = "Wooden panels and paint"
}

func (b *WoodHouseBuilder) GetHouse() House {
    return b.house
}

4 - Defining the Director

The Director is a class that manages the construction of an object, ensuring that the construction steps are called in the correct order. It knows nothing about the details of specific Builder implementations, it just calls Builder methods in a logical sequence to create the final product.

//director.go

package main

type Director struct {
    builder HouseBuilder
}

func (d *Director) Build() {
    d.builder.SetFoundation()
    d.builder.SetStructure()
    d.builder.SetRoof()
    d.builder.SetInterior()
}

func (d *Director) SetBuilder(b HouseBuilder) {
    d.builder = b
}

5 - Using the Builder

Finally, we will use the Director and concrete Builders to build different types of houses.

//main.go

package main

import (
    "fmt"
)

func main() {
    cb := &builder.ConcreteHouseBuilder{}
    director := builder.Director{Builder: cb}

    director.Build()
    concreteHouse := cb.GetHouse()

    fmt.Println("Concrete House")
    fmt.Println("Foundation:", concreteHouse.Foundation)
    fmt.Println("Structure:", concreteHouse.Structure)
    fmt.Println("Roof:", concreteHouse.Roof)
    fmt.Println("Interior:", concreteHouse.Interior)
    fmt.Println("-------------------------------------------")

    wb := &builder.WoodHouseBuilder{}
    director.SetBuilder(wb)

    director.Build()
    woodHouse := wb.GetHouse()

    fmt.Println("Wood House")
    fmt.Println("Foundation:", woodHouse.Foundation)
    fmt.Println("Structure:", woodHouse.Structure)
    fmt.Println("Roof:", woodHouse.Roof)
    fmt.Println("Interior:", woodHouse.Interior)
}

In short

  1. Struct House: Represents the final product we are building.
  2. HouseBuilder Interface: Defines the methods for building the different parts of the house.
  3. Concrete Implementations (ConcreteHouseBuilder and WoodHouseBuilder): Implement the HouseBuilder interface and define specific construction steps.
  4. Director: Manages the construction process, ensuring that the steps are called in the correct order.
  5. Main function: Demonstrates the use of the Builder pattern to build different types of houses, calling the Director to manage the process and obtaining the final product.

Conclusion

The Builder pattern is a tool for building complex objects in an incremental and flexible way. In Golang, the implementation of this pattern is direct and effective, allowing the creation of modular and easy-to-maintain systems. By using concrete interfaces and classes, we can centralize construction logic and simplify code evolution as new requirements emerge.

The above is the detailed content of Builder Design 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
Golang's Impact: Speed, Efficiency, and SimplicityGolang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C   and Golang: When Performance is CrucialC and Golang: When Performance is CrucialApr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang in Action: Real-World Examples and ApplicationsGolang in Action: Real-World Examples and ApplicationsApr 12, 2025 am 12:11 AM

Golang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.

Golang: The Go Programming Language ExplainedGolang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AM

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

Golang's Purpose: Building Efficient and Scalable SystemsGolang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PM

Confused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...

Is technology stack convergence just a process of technology stack selection?Is technology stack convergence just a process of technology stack selection?Apr 02, 2025 pm 05:21 PM

The relationship between technology stack convergence and technology selection In software development, the selection and management of technology stacks are a very critical issue. Recently, some readers have proposed...

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment