设计模式-建造者模式

  1. 生成者模式 Build

生成者模式 Build

将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示

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

/**
* @USER: lynn
* @DATE: 2020/4/26
**/
public class Build {
public static void main(String[] args) {
Car audi = new Car.Builder()
.color(Color.BLACK)
.money(300000)
.kind("A4")
.year(2020)
.build();
System.out.println(audi.getMoney());
}
}

class Car{
String kind;
Color color;
int year;
int money;

private Car(Builder builder) {
setKind(builder.kind);
setColor(builder.color);
setYear(builder.year);
setMoney(builder.money);
}

public String getKind() {
return kind;
}

public void setKind(String kind) {
this.kind = kind;
}

public Color getColor() {
return color;
}

public void setColor(Color color) {
this.color = color;
}

public int getYear() {
return year;
}

public void setYear(int year) {
this.year = year;
}

public int getMoney() {
return money;
}

public void setMoney(int money) {
this.money = money;
}


public static final class Builder {
private String kind;
private Color color;
private int year;
private int money;

public Builder() {
}

public Builder kind(String val) {
kind = val;
return this;
}

public Builder color(Color val) {
color = val;
return this;
}

public Builder year(int val) {
year = val;
return this;
}

public Builder money(int val) {
money = val;
return this;
}

public Car build() {
return new Car(this);
}
}
}
  • 应用场景
    • Android中,对话框的创建
    • OkHttp
  • 优点
    • 避免过多setter方法,并且隐藏内部细节
    • 链式调用,简洁易懂。
  • 缺点
    • 内部类与外部类相互引用,可能会导致内存消耗比较大

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 yanglau0527@gmail.com

文章标题:设计模式-建造者模式

文章字数:318

本文作者:Cynaith

发布时间:2020-05-02, 01:22:36

最后更新:2020-05-02, 01:25:45

原始链接:https://cynaith.github.io/2020/05/02/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E5%BB%BA%E9%80%A0%E8%80%85%E6%A8%A1%E5%BC%8F/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏