This is a creation in Article, where the information may have evolved or changed.
This series of articles will use simple examples to introduce the implementation of the go language design pattern.
Simple Factory mode definition
- The factory pattern provides the ability to create specific instances where the user does not need to be concerned about their specific implementation.
Applicable scenarios
- The client is not aware of the specific implementation of the internal, only the factory can contact the implementation details. The returned instance can be an interface, a specific type, and so on.
Simple example
- Use the factory model to find the side length and area of the geometry.
Package MainImport ("FMT""Math")type Geometrytype intConst (Geometryrect Geometrytype = Iotageometrycicle)type Geometry Interface { Area() float32Perim() float32}type Rectangle struct {width, Height float32}func (R *Rectangle) Area() float32 {return R.width * R.Height}func (R *Rectangle) Perim() float32 {return 2*R.width + 2*R.Height}type Circle struct {radius float32}func (C *Circle) Area() float32 {return Math.Pi * C.radius * C.radius}func (C *Circle) Perim() float32 {return 2 * Math.Pi * C.radius}type Params struct {width float32Height float32radius float32}func Newgeometry(params *Params, Geo Geometrytype) Geometry {Switch Geo { Case geometrycicle:return &Circle{radius: params.radius,} Case Geometryrect:return &Rectangle{Height: params.Height,width: params.width,}default://Type error}return Nil}func Main() {Geo := Newgeometry(&Params{radius: 3.0}, geometrycicle)FMT.Println(Geo. Area())FMT.Println(Geo.Perim())return}
Advantages and disadvantages of the simple factory model
Advantages
- Help encapsulation for interface-oriented programming
- Decoupling clients from specific implementation classes
Disadvantages
- Selecting a specific implementation class from the parameters passed in by the client requires the client to be able to understand the meaning of the parameter, which increases the complexity of the client
- Inconvenient to extend sub-factory
My public number: easyhacking
Go design mode is updated in succession github:csxuejin/go-design-patterns