From: AceVest Date: Tue, 23 Nov 2021 04:07:37 +0000 (+0800) Subject: add go abstract factory X-Git-Url: http://zhaoyanbai.com/repos/cppcheck-error.log?a=commitdiff_plain;h=2cf4c2d7c9a06543c41125447d42f95a6226a8b1;p=acecode.git add go abstract factory --- 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