상세 컨텐츠

본문 제목

27/02 Builder pattern in GO - Construct the ship's Defense Shields

Go/Study record

by Gopythor 2022. 2. 27. 21:32

본문

728x90
반응형

What is the Builder Pattern?

Creational pattern
Build complicated objects piect by piece

  • So what is the builder pattern?
  • It is considered a creational pattern like the factory pattern.
  • However it differs when it comes to how it builds an object.
  • The builder pattern is used to create an object by putting its pieces together first before instaniating it.
  • The pattern relies on a builder object which composes the components of the other object one by one before it builds it.

Why use the Builder Pattern?

Avoid complex constructors
Some objects are not easily edited after being created

  • So why is that important?
  • There are multiple reasons as usual but one of the more visible advantages is the fact that when we use a builder to build a complex object, we avoid having a large constructor to build this complex object.
  • Another reason is that some objects are not easily edited after being created like JSON data for example.
  • So it is better to collect all the information first via builder then build the complex object once.
  • So how to implement the builder pattern in Go then.
  • It is simple.

shieldBuilder.go

type shield struct {
    front bool
    back  bool
    right bool
    left  bool
}

type shBuilder struct {
    code string
}

//NewShieldBuilder is a constructor for a new shield builder
func NewShieldBuilder() *shBuilder {
    return new(shBuilder)
}

func (sh *shBuilder) RaiseFront() *shBuilder {
    sh.code += "F"
    return sh
}

func (sh *shBuilder) RaiseBack() *shBuilder {
    sh.code += "B"
    return sh
}

func (sh *shBuilder) RaiseRight() *shBuilder {
    sh.code += "R"
    return sh
}

func (sh *shBuilder) RaiseLeft() *shBuilder {
    sh.code += "L"
    return sh
}

func (sh *shBuilder) Build() *shield {
    code := sh.code
    return &shield{
        front: strings.Contains(code, "F")
        back: strings.Contains(code, "B")
        right: strings.Contains(code, "R")
        left: strings.Contains(code, "L")
    }
}
  • Let's write a program for the hydra spaceship which is test for building a space shield.
  • We will use as shBuilder to collect the information necessary.
  • Then when build is requested, We will build the shield
  • That builder will build a shield object based on their information it has.
  • The shield struct will have four flags. Front, Back, Right and Left.
  • Each one were present a part of our ship.
  • So if one is true then we know that the shield is up in this position of the spaceship.
  • Otherwise shields are down.
  • The shBuiler struct will include code which will use to identify how the shield will look like.
  • Let's write a constructor to obtain a shield builder.
  • We'll then write for methods attached to the shBuilder struct.
  • Each method will present a command to raise a shield in a specific position.
  • So for example, RaiseFront will raise the shield at the front of the ship and so forth.
  • With each method that builder will attach a character representing the position as shown.
  • "F" for front, "B" for back, " R" for right and "L" for left.
  • Each of our methods will return a pointer to the shBuilder.
  • Now we write the build function of our builder which for return a shield pointer type.
  • We will use a struct literial to create the shield object inside the struct literial.
  • We will use a string package to inspect the code available in the shBuilder.
  • Then based on that code, we'll set the appropriate flag in the shield struct.
  • That contains function will return true or false Boolean indicating whether this character exists in our shield code.
  • An important remark that worth noting is that we could have implemented this exercise using some bit math????
  • However we decided to use that strings because it's more straightforward.

func main()

func main() {
    builder := NewShieldBuilder()
    shield := builder.RaiseLeft().RaiseFront().Build()
    fmt.Printf("%+v \n", *shield)
}

https://go.dev/play/p/iNrB99nY8Lc

Print result

{front:true back:false right:false left:true} 
  • Let's use Go's playground.
  • So remember that everyting needs to be in the main package so the we can run our code here.
  • So one advantage of writing the builder code the way we did where for all our Raise shield methods.
  • We returned a pointer to the shBuilder.
  • Is the fact that we can chain our calls like this and then call build at the end.
  • This looks much nicer.
  • So in here we raise the left shield and then the front shield.
  • We can then use the fmt.Printf to print the results.
  • The reason why we use the * asterisk keword because we are dereferencing the shield pointer.
  • So we're getting the value behind the pointer.
  • The percentage plus V is a way to present a struct with the field and the values as we'll see very shortly.
  • The slash n(\n) is the end of line.
  • So if we hit run, we'll see a full presention of our shield struct so we can see here that the front is true as well as the left which is exactly what we raised here.
  • So we raised left and then RaiseFront.
  • out builder works as expected.

Summary

-we have explored
Advanced features in methods and interfaces
Object-Oriented programming in the Go world
some poplular design patterns

  • We covered the builder pattern in Go and explore the ease by which we can write object oriented design patterns in the language.
  • In this section we do depper into the world of object-oriented programming combined with Go
  • We witnessed how even though Go doesn't have classes it still posseses powerful features that allow us to write modern a well-designed object oriented software.
  • We explored the factory pattern which is used to create objects via factory method instead of directly
  • The singleton pattern as well we explored which is used to ensure only a single instance of a specific object exists in our program.
  • And lastly we explored the builder pattern which is used to build complex objects from other objects called Builders.

Section 4: Object-Oriented Patterns in the Go World 22 Builder Pattern in Go – Construct the Ship’s Defense Shields
from Mastering Go Programming

728x90
반응형

'Go > Study record' 카테고리의 다른 글

Sprint는 어떤 때 사용되는가?  (0) 2022.03.26
Quick Sort in Go  (0) 2022.03.17
28/2 Struct Pointer study  (0) 2022.03.01
28/2 mixture of field:value and value initializers error in Go  (0) 2022.02.28

관련글 더보기

댓글 영역