The schema definition

Separating the creation of a complex object from its representation allows the same build process to create different representations

The class diagram

Application scenarios

1. The object to be generated has a complex internal structure;

2. The internal attributes of objects that need to be generated are interdependent;

3. Used with immutable objects;


1. Independent builder, easy to expand;

2. Easy to control the risk of details;

The point to summarize

  • The Builder pattern is primarily used to “build a complex object in steps,” where “steps” are a stable algorithm, while the parts of a complex object change frequently
  • Where is the change point, where is the encapsulation —-Builder mode is mainly to deal with the “complex object each part” frequent demand changes, its disadvantage is difficult to deal with the “step by step construction algorithm” demand changes

Go language code implementation

Project directory


Package Builder Type Builder Interface {Part1() Part2() Part3())} Type Director struct {Builder Builder // Package Builder Type Builder Interface {Part1() Part2() Part3())} // create interface func newDirector (Builder Builder) *Director {return &Director{Builder: builder} } func (d *Director) Makedata(){ d.builder.Part1() d.builder.Part2() d.builder.Part3() }


package Builder

type StringBuilder struct {
   result string

func (sb *StringBuilder) Part1 ()  {
   sb.result += "1"

func (sb *StringBuilder) Part2 ()  {
   sb.result += "2"

func (sb *StringBuilder) Part3 ()  {
   sb.result += "3"

func (sb *StringBuilder) GetResult() string {
   return sb.result


package Builder

type IntBuilder struct {
   result int64

func (ib *IntBuilder) Part1 ()  {
   ib.result += 1

func (ib *IntBuilder) Part2 ()  {
   ib.result += 2

func (ib *IntBuilder) Part3 ()  {
   ib.result += 3

func (ib *IntBuilder) GetResult() int64 {
   return ib.result


package Builder

import (

func TestIntBuilder(t *testing.T) {
   sbuilder := &StringBuilder{}
   dict := NewDirector(sbuilder)

   ibuilder := &IntBuilder{}
   dict = NewDirector(ibuilder)