Skip to content

Instantly share code, notes, and snippets.

@yifanes
Created July 22, 2019 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yifanes/b1fca0dbda2c4671dddace63c4feaf7e to your computer and use it in GitHub Desktop.
Save yifanes/b1fca0dbda2c4671dddace63c4feaf7e to your computer and use it in GitHub Desktop.
golang工厂方法
package main
import "fmt"
type Operator interface {
SetA(int)
SetB(int)
Result() int
}
type OperatorFactory interface {
Create() Operator
}
type BaseData struct {
a, b int
}
func (base *BaseData) SetA(a int) {
base.a = a
}
func (base *BaseData) SetB(b int) {
base.b = b
}
type PlusOperateFactory struct {}
func (PlusOperateFactory) Create() Operator {
return &PlusOperate{
BaseData:BaseData{},
}
}
type PlusOperate struct {
BaseData
}
func (p PlusOperate) Result() int {
return p.a + p.b
}
type RemoveOperate struct {
BaseData
}
func (r RemoveOperate) Result() int {
return r.a - r.b
}
func main() {
r := RemoveOperate{BaseData{}}
r.SetA(1)
r.SetB(19)
fmt.Println(r.Result())
factory := PlusOperateFactory{}.Create()
factory.SetA(1)
factory.SetB(2)
fmt.Println(factory.Result())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment