The schema definition

Define an interface for creating objects, let subclasses decide which classes to instantiate, and defer instantiation of a class to subclasses

The class diagram

Application scenarios

1. When you don’t know the exact type of object to use;

2. When you want to provide a way for a library or framework to extend its internal components.

The main advantages

1. Decouple the product from the creator;

2. Comply with the principle of single responsibility;

3. Comply with the Open Closed Principle.

The point to summarize

  • The Factory Method pattern is used to isolate the coupling between a consumer of a class object and a concrete type. Tightly coupled (NEW) relationships can lead to software vulnerability in the face of a concrete type that changes frequently
  • Factory Method pattern uses object-oriented approach to delay the work of the concrete object to be created to subclasses, so as to realize a strategy of extension (rather than change), which solves this tight coupling relationship
  • The Factory Method pattern liberates the “single object” requirement variation. The drawback is that it requires the creation of methods with the same parameters

Go language implementation

Project directory

OperatorFactory.go

Package Factory // Type Operator Interface {setLeft (int) setRight (int) Result() int} // Factory interface type Operator Interface {setLeft (int) setRight (int) Result() int} // Factory interface type OperatorFactory interface { Create() Operator }

OperatorData.go

Package Factory // data type OperatorData struct {left, Right int} setLeft (left int) {op.left = left} func (op *OperatorData) setRight (right) int) { op.right = right }

PlusOpertaorFactory.go

Package Factory // Operate type PlusOpertaorFactory struct {} // Operate type PlusOpertaorFactory struct {*OperatorData} Func (o PlusOpertaOr) Result() int {return O.Right + O.Left} func(PlusOpertaOrFactory) Create() Operator { return &PlusOpertaor{&OperatorData{}} }

SubOpertaorFactory.go

Package Factory // The abstract type subopertaorFactory struct {} // The operation class contains the operand type SubOpertaor struct {*OperatorData} // The actual method to run  func(o SubOpertaor) Result() int { return o.left - o.right } func(SubOpertaorFactory) Create() Operator { return &SubOpertaor{&OperatorData{}} }

factory_test.go

package Factory

import (
   "fmt"
   "testing"
)

func TestOpertaorFactory(t *testing.T) {
   var fac OperatorFactory
   fac = PlusOpertaorFactory{}
   op := fac.Create()
   op.SetLeft(20)
   op.SetRight(10)
   fmt.Println(op.Result())

   fac = SubOpertaorFactory{}
   op = fac.Create()
   op.SetLeft(30)
   op.SetRight(20)
   fmt.Println(op.Result())
}