设计模式-抽象工厂模式golang实现

抽象工厂模式

抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package abstractfactorypattern

type Shape interface {
Draw() string
}

type Rectangle struct{}

func (r *Rectangle) Draw() string {
return "rectangle"
}

type Square struct{}

func (s *Square) Draw() string {
return "square"
}

type Circle struct{}

func (c *Circle) Draw() string {
return "circle"
}


type Color interface {
fill() string
}

type Red struct{}

func (r *Red) fill() string {
return "Red"
}

type Green struct{}

func (r *Green) fill() string {
return "Green"
}

type Blue struct{}

func (r *Blue) fill() string {
return "Blue"
}

//AbstractFactory 抽象工厂接口
type AbstractFactory interface {
NewFactoryShape(t string) Shape
NewFactoryColor(t string) Color
}

type ShapeFactory struct{}
type ColorFactory struct{}

func (s *ShapeFactory) NewFactoryShape(t string) Shape {
if t == "" {
return nil
}
switch t {
case "rectangle":
return new(Rectangle)
case "square":
return new(Square)
case "circle":
return new(Circle)
}
return nil
}
func (s *ShapeFactory) NewFactoryColor(t string) Color {
return nil
}

func (c *ColorFactory) NewFactoryColor(t string) Color {
if t == "" {
return nil
}
switch t {
case "red":
return new(Red)
case "green":
return new(Green)
case "blue":
return new(Blue)
}
return nil
}

func (c *ColorFactory) NewFactoryShape(t string) Shape {
return nil
}

//FactoryProducer 超级工厂类,用于获取工厂实例
func FactoryProducer(factory string) AbstractFactory {
if factory == "" {
return nil
}
switch factory {
case "color":
return new(ColorFactory)
case "shape":
return new(ShapeFactory)
default:
return nil
}
}

test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package abstractfactorypattern

import "testing"

func TestShape(t *testing.T) {
factory := FactoryProducer("shape")
if factory == nil {
t.Fatal("error")
}
shape := factory.NewFactoryShape("square")
if shape == nil {
t.Fatal("error")
}
if res := shape.Draw(); res != "square" {
t.Errorf("error, wanted: %v, got: %v", "square", res)
}
}

func TestColor(t *testing.T) {
factory := FactoryProducer("color")
if factory == nil {
t.Fatal("error")
}
color := factory.NewFactoryColor("red")
if color == nil {
t.Fatal("error")
}
if res := color.fill(); res != "Red" {
t.Errorf("error, wanted: %v, got: %v", "Red", res)
}
}

代码地址

参考

Search by:GoogleBingBaidu