From 672e565428d821216ce7cf86d7e10b26346b783a Mon Sep 17 00:00:00 2001 From: Edward Date: Mon, 27 Apr 2020 11:55:19 +0800 Subject: [PATCH] finish abstractfactory :Robot & Battery --- .../abstractfactory_robot.go | 69 +++++++++++++++++++ .../abstractfactory_test.go | 9 +++ 2 files changed, 78 insertions(+) create mode 100644 creation/05_abstract_factory/abstractfactory_robot.go diff --git a/creation/05_abstract_factory/abstractfactory_robot.go b/creation/05_abstract_factory/abstractfactory_robot.go new file mode 100644 index 0000000..3e7056b --- /dev/null +++ b/creation/05_abstract_factory/abstractfactory_robot.go @@ -0,0 +1,69 @@ +package abstractfactory + +import "fmt" + +//IRobot : 机器人能做的事情 +type IRobot interface { + Name() string + DoWork() + //.....BALABALA..可以继续写很多接口方法 + //每个接口方法做一件事 +} + +//IBattery 电池能做的事情 +type IBattery interface { + Charge(robot IRobot) + //.....BALABALA..可以继续写很多接口方法 + //每个接口方法做一件事 +} + +//IProduce 是当抽象工厂模式例子中的关键接口 +//IProduce 返回一组产品对象 +//IProduce 本质是创建工作对象,但必须以接口方式返回 +type IProduce interface { + CreateRobot() IRobot + CreateBattery() IBattery + //.....BALABALA..可以继续写很多接口方法 + //每个接口方法都要返回一个接口 +} + +//////////////////////////////// +//接口定义好了,开始进行实现和应用 +//////////////////////////////// + +//HomeRobot 家用机器人 +type HomeRobot struct{} + +//DoWork 机器人可以做工作 +func (*HomeRobot) DoWork() { + fmt.Print("robot is cleaning home\n") +} + +//Name 机器人的名字 +func (*HomeRobot) Name() string { + return fmt.Sprint("home robot") +} + +//HomeBattery 家用电池 +type HomeBattery struct{} + +// Charge SaveOrderDetail接口,保存订单细节 +func (*HomeBattery) Charge(robot IRobot) { + + rn := robot.Name() + fmt.Print("HomeBattery is charging for:", rn) + fmt.Println() +} + +//HomeRobotFactory 家用机器人工厂 +type HomeRobotFactory struct{} + +//CreateRobot 创建机器人 +func (*HomeRobotFactory) CreateRobot() IRobot { + return &HomeRobot{} +} + +//CreateBattery 创建电池 +func (*HomeRobotFactory) CreateBattery() IBattery { + return &HomeBattery{} +} diff --git a/creation/05_abstract_factory/abstractfactory_test.go b/creation/05_abstract_factory/abstractfactory_test.go index a70e1f2..61a6652 100644 --- a/creation/05_abstract_factory/abstractfactory_test.go +++ b/creation/05_abstract_factory/abstractfactory_test.go @@ -2,6 +2,15 @@ package abstractfactory import "testing" +func TestRobotBatteryFactory(t *testing.T) { + + factory := &HomeRobotFactory{} + robot := factory.CreateRobot() + robot.DoWork() + battery := factory.CreateBattery() + battery.Charge(robot) +} + func TestSQLFactory(t *testing.T) { factory := &SQLFactory{}