From 2cf4c2d7c9a06543c41125447d42f95a6226a8b1 Mon Sep 17 00:00:00 2001 From: AceVest Date: Tue, 23 Nov 2021 12:07:37 +0800 Subject: [PATCH] add go abstract factory --- .../abstract_factory/abstract_factory.go | 50 +++++++++++++++++++ .../abstract_factory/abstract_factory_test.go | 31 ++++++++++++ learn/go/patterns/go.mod | 3 ++ 3 files changed, 84 insertions(+) create mode 100644 learn/go/patterns/abstract_factory/abstract_factory.go create mode 100644 learn/go/patterns/abstract_factory/abstract_factory_test.go create mode 100644 learn/go/patterns/go.mod diff --git a/learn/go/patterns/abstract_factory/abstract_factory.go b/learn/go/patterns/abstract_factory/abstract_factory.go new file mode 100644 index 0000000..2cf15c4 --- /dev/null +++ b/learn/go/patterns/abstract_factory/abstract_factory.go @@ -0,0 +1,50 @@ +/* + * ------------------------------------------------------------------------ + * File Name: abstract_factory.go + * Author: Zhao Yanbai + * 2021-11-23 11:27:27 Tuesday CST + * Description: 抽象工厂模式 + * ------------------------------------------------------------------------ + */ + +package abstract_factory + +type Product interface { + Label() string +} + +type Factory interface { + CreateProduct() Product +} + +type CarFactory struct{} +type ComputerFactory struct{} +type GameFactory struct{} + +func (f CarFactory) CreateProduct() Product { + return &Car{} +} + +func (f ComputerFactory) CreateProduct() Product { + return &Computer{} +} + +func (f GameFactory) CreateProduct() Product { + return &Game{} +} + +type Car struct{} +type Computer struct{} +type Game struct{} + +func (c Car) Label() string { + return "car" +} + +func (c Computer) Label() string { + return "computer" +} + +func (g Game) Label() string { + return "game" +} diff --git a/learn/go/patterns/abstract_factory/abstract_factory_test.go b/learn/go/patterns/abstract_factory/abstract_factory_test.go new file mode 100644 index 0000000..400a5e8 --- /dev/null +++ b/learn/go/patterns/abstract_factory/abstract_factory_test.go @@ -0,0 +1,31 @@ +/* + * ------------------------------------------------------------------------ + * File Name: abstract_factory_test.go + * Author: Zhao Yanbai + * 2021-11-23 11:37:13 Tuesday CST + * Description: none + * ------------------------------------------------------------------------ + */ + +package abstract_factory + +import "testing" +import "log" + +func Test(t *testing.T) { + + var factorys = []Factory{ + &CarFactory{}, + &ComputerFactory{}, + &GameFactory{}, + } + + var factory Factory + var product Product + + for _, factory = range factorys { + product = factory.CreateProduct() + log.Printf("%v", product.Label()) + } + +} diff --git a/learn/go/patterns/go.mod b/learn/go/patterns/go.mod new file mode 100644 index 0000000..f10fbaa --- /dev/null +++ b/learn/go/patterns/go.mod @@ -0,0 +1,3 @@ +module patterns + +go 1.16 -- 2.44.0