Created
July 22, 2019 03:19
-
-
Save yifanes/b1fca0dbda2c4671dddace63c4feaf7e to your computer and use it in GitHub Desktop.
golang工厂方法
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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