]> Zhao Yanbai Git Server - acecode.git/commitdiff
add go abstract factory
authorAceVest <zhaoyanbai@126.com>
Tue, 23 Nov 2021 04:07:37 +0000 (12:07 +0800)
committerAceVest <zhaoyanbai@126.com>
Tue, 23 Nov 2021 04:07:37 +0000 (12:07 +0800)
learn/go/patterns/abstract_factory/abstract_factory.go [new file with mode: 0644]
learn/go/patterns/abstract_factory/abstract_factory_test.go [new file with mode: 0644]
learn/go/patterns/go.mod [new file with mode: 0644]

diff --git a/learn/go/patterns/abstract_factory/abstract_factory.go b/learn/go/patterns/abstract_factory/abstract_factory.go
new file mode 100644 (file)
index 0000000..2cf15c4
--- /dev/null
@@ -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 (file)
index 0000000..400a5e8
--- /dev/null
@@ -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 (file)
index 0000000..f10fbaa
--- /dev/null
@@ -0,0 +1,3 @@
+module patterns
+
+go 1.16