go-pattern-examples/creation/05_factory_method/factorymethod.go

85 lines
1.7 KiB
Go
Raw Normal View History

2020-04-21 17:50:21 +03:00
package factorymethod
2020-04-24 06:15:47 +03:00
import (
"fmt"
"strconv"
)
2020-04-23 07:23:28 +03:00
//Assistant 是robot能做的事情
type Assistant interface {
Clean(int)
Speak(string)
Work() string
2020-04-21 17:50:21 +03:00
}
2020-04-23 07:23:28 +03:00
//IRobotFactory must be implemented by Factory
//different Factory create different robot
type IRobotFactory interface {
Build() Assistant
2020-04-21 17:50:21 +03:00
}
2020-04-23 07:23:28 +03:00
//BasicRobotModel 是基本的机器人模型
type BasicRobotModel struct {
2020-04-24 06:15:47 +03:00
words string
workTime int
2020-04-21 17:50:21 +03:00
}
2020-04-23 07:23:28 +03:00
//Clean 打扫
2020-04-24 06:15:47 +03:00
func (b *BasicRobotModel) Clean(a int) {
b.workTime = a
fmt.Printf("i can clean :%d hours\n", a)
2020-04-21 17:50:21 +03:00
}
2020-04-23 07:23:28 +03:00
//Speak 说话
2020-04-24 06:15:47 +03:00
func (b *BasicRobotModel) Speak(w string) {
b.words = w
fmt.Printf("my name is: %s\n", w)
2020-04-21 17:50:21 +03:00
}
2020-04-23 07:23:28 +03:00
//Work main work
2020-04-24 06:15:47 +03:00
func (b *BasicRobotModel) Work() string {
return fmt.Sprint("my main work is do somthing")
2020-04-23 07:23:28 +03:00
}
//FightingRobotFactory 生产各类军工机器人
type FightingRobotFactory struct{}
2020-04-21 17:50:21 +03:00
2020-04-23 07:23:28 +03:00
//Build a robot from FightingRobotFactory
func (FightingRobotFactory) Build() Assistant {
2020-04-24 06:15:47 +03:00
return &FightingRobot{
BasicRobotModel: &BasicRobotModel{},
2020-04-21 17:50:21 +03:00
}
}
2020-04-23 07:23:28 +03:00
//FightingRobot 实际的战斗机器人
type FightingRobot struct {
*BasicRobotModel
2020-04-21 17:50:21 +03:00
}
2020-04-24 06:15:47 +03:00
//Work for FightingRobot to do some fighting
func (f FightingRobot) Work() string {
fmt.Printf("%s\n", "i can fighting")
return "i can fighting" + strconv.Itoa(f.workTime)
2020-04-21 17:50:21 +03:00
}
2020-04-23 07:23:28 +03:00
//HomeRobotFactory 生产各类家用机器人
type HomeRobotFactory struct{}
2020-04-21 17:50:21 +03:00
2020-04-23 07:23:28 +03:00
//Build a robot from HomeRobotFactory
func (HomeRobotFactory) Build() Assistant {
2020-04-24 06:15:47 +03:00
return &HomeRobot{
BasicRobotModel: &BasicRobotModel{},
2020-04-21 17:50:21 +03:00
}
}
2020-04-23 07:23:28 +03:00
//HomeRobot 实际的家用机器人
type HomeRobot struct {
2020-04-24 06:15:47 +03:00
*BasicRobotModel
2020-04-21 17:50:21 +03:00
}
2020-04-24 06:15:47 +03:00
//Work robot do some work
func (h HomeRobot) Work() string {
fmt.Printf("%s\n", "i can do homework")
return "i can do homework" + strconv.Itoa(h.workTime)
2020-04-21 17:50:21 +03:00
}