造者模式Golang

造者模式(Builder Pattern)

将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
抽象建造者类中定义了产品的创建方法和返回方法.
建造者模式的结构中还引入了一个指挥者类Director,该类的作用主要有两个:一方面它隔离了客户与生产过程;
另一方面它负责控制产品的生成过程。指挥者针对抽象建造者编程,客户端只需要知道具体建造者的类型,
即可通过指挥者类调用建造者的相关方法,返回一个完整的产品对象.

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
type Wheel int
type Vehicle struct {
Wheels Wheel
Seats int
Structure string
}

//builder interface
type Builder interface {
SetWheels() Builder
SetSeats() Builder
SetStructure() Builder
GetVehicle() Vehicle
}

//Director
type Director struct {
builder Builder
}

func (director *Director) Construct() {
director.builder.SetWheels().SetSeats().SetStructure() //链式调用
}

func (director *Director) SetBuilder(builder Builder) {
director.builder = builder
}

//car struct
type Car struct {
vehicle Vehicle
}

func (car *Car) SetWheels() Builder {
car.vehicle.Wheels = 4
return car
}
func (car *Car) SetSeats() Builder {
car.vehicle.Seats = 4
return car
}
func (car *Car) SetStructure() Builder {
car.vehicle.Structure = "Car"
return car
}
func (car *Car) GetVehicle() Vehicle {
return car.vehicle
}

Powered by Hexo and Hexo-theme-hiker

Copyright © 2018 - 2021 Noonde All Rights Reserved.

UV : | PV :