technique that allows to encapsulate construction logic for an object while creating
break up construction of complex object into smaller parts and decople construction from its representation that can be reused to create different representations
type Message struct { Body []byte Format MessageFormat } type MessageBuilder interface { SetRecepient(recepient string) SetText(text string) Build() (*Message, error) } type JsonBuilder struct { recepient string text string }
func(s *Sender)BuildMessage(mb MessageBuilder)(*Message, error) { mb.SetRecepient("Santa Claus") mb.SetText("I was a good body, give me a gift!") return mb.Build() }
The main idea is next:
MessageFormat defines two formats of message(xml, json)
Message type define two fields(body of message and format)
MessageBuilder common interface for builder object with corresponding methods for setters and Build() function
JsonBuilder and XmlBuilder are concrete implementations MessageBuilder interface. It creates messages in two different formats
Sender is director class that creates message. It accepts a MessageBuilder type and build it. And it doesn’t really matter what exactly type of MessageBuilder
Basic usage. Define director class and pass two different builders of MessageBuilder type.
1 2 3
go run . {"recepient":"Santa Claus","text":"I was a good body, give me a gift!"} <XMLMessage><recipient>Santa Claus</recipient><body>I was a good body, give me a gift!</body></XMLMessage>