Builder

Sometimes, object creation is not so straightforward. For example:

  • It might be necessary to have business rules to validate some parameters or derive some added attributes. For example, in a reservation, we might derive a nonCancellable attribute based on the vertical, seller, and travel date details.
  • We might need some code to bring in efficiency—for example, retrieving an object from the cache rather than reading from the DB.
  • It might be necessary to have idempotency and thread safety in object creation. That is, multiple requests for object creation with the same parameters should give the same object.
  • The objects might have multiple constructor arguments (typically called telescopic constructors), and it is difficult to remember the order of parameters for the clients. Some of these parameters might be optional. Such constructors frequently lead to bugs in client code.

The builder pattern allows you to create different flavors of an object while enforcing the constraints mentioned previously. For our reservation example, the builder will look like this:

type ReservationBuilder interface {
Vertical(string) ReservationBuilder
ReservationDate(string) ReservationBuilder
Build() Reservation
}

type reservationBuilder struct {
vertical string
rdate string
}

func (r *reservationBuilder) Vertical(v string) ReservationBuilder {
r.vertical = v
return r
}

func (r *reservationBuilder) ReservationDate(date string) ReservationBuilder {
r.rdate = date
return r
}

func (r *reservationBuilder) Build() Reservation {
var builtReservation Reservation

switch r.vertical {
case "flight":
builtReservation = FlightReservationImpl{r.rdate}
case "hotel":
builtReservation = HotelReservationImpl{r.rdate}
}

return builtReservation
}

func NewReservationBuilder() ReservationBuilder {
return &reservationBuilder{}
}

As you can see, our object creation is much more powerful. The lazy creation (after we have all the arguments) also helps us exploit efficiency goals; for example, loading an expensive-to-create object from the cache.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset