Abstract factory

With real-life problems, there are many related (family of) objects that need to be created together. For example, if our travel website decides to give away invoices for reservations, then with our two verticals we essentially have the following:

  • Two types of entities: reservation and invoice
  • Two verticals/types of products: hotel and flight

When the client code is creating such related products, how do we ensure that clients don't make mistakes (for example, associating a flight invoice to a hotel reservation)? The simple factory method does not cut it here, since the client would need to figure out all the right factories needed for each type of entity/object.

The abstract factory pattern attempts to solve this issue with a factory of factories construct: a factory that groups the different related/dependent factories together without specifying their concrete classes:

An implementation of an abstract factory with the reservation/invoice:

// We have Reservation and Invoice as two generic products
type Reservation interface{}
type Invoice interface{}

type AbstractFactory interface {
CreateReservation() Reservation
CreateInvoice() Invoice
}

type HotelFactory struct{}

func (f HotelFactory) CreateReservation() Reservation {
return new(HotelReservation)
}

func (f HotelFactory) CreateInvoice() Invoice {
return new(HotelInvoice)
}

type FlightFactory struct{}

func (f FlightFactory) CreateReservation() Reservation {
return new(FlightReservation)
}

func (f FlightFactory) CreateInvoice() Invoice {
return new(FlightReservation)
}


type HotelReservation struct{}
type HotelInvoice struct{}
type FlightReservation struct{}
type FlightInvoice struct{}

func GetFactory(vertical string) AbstractFactory {
var factory AbstractFactory
switch vertical {
case "flight":
factory = FlightFactory{}
case "hotel":
factory = HotelFactory{}
}

return factory
}

The client can use the abstract factory as follows:

hotelFactory:= GetFactory("hotel")
reservation:= hotelFactory.CreateReservation()
invoice:= hotelFactory.CreateInvoice()

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

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