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

工厂模式

工厂模式(Factory Pattern)属于创建型模式,它提供了一种创建对象的最佳方式。

在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。

golang实现

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
package factorypattern

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"
}

// NewShapeFactory 用于生成Shape接口实例
func NewShapeFactory(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
}

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
32
33
34
35
36
package factorypattern

import "testing"

func TestRectangle(t *testing.T) {
rectangle := NewShapeFactory("rectangle")
if rectangle == nil {
t.Fatal("factory new failed")
}
res := rectangle.Draw()
if res != "rectangle" {
t.Errorf("error, wanted: %v, got: %v", "rectangle", res)
}
}

func TestSquare(t *testing.T) {
square := NewShapeFactory("square")
if square == nil {
t.Fatal("factory new failed")
}
res := square.Draw()
if res != "square" {
t.Errorf("error, wanted: %v, got: %v", "square", res)
}
}

func TestCircle(t *testing.T) {
circle := NewShapeFactory("circle")
if circle == nil {
t.Fatal("factory new failed")
}
res := circle.Draw()
if res != "circle" {
t.Errorf("error, wanted: %v, got: %v", "circle", res)
}
}

代码地址

https://github.com/luckylsx/golang-design-mode/tree/main/01_FactoryPattern

参考

https://www.runoob.com/design-pattern/factory-pattern.html

Search by:GoogleBingBaidu