定义:将一个复杂对象的构建与它的表示分离,使得一样的构建过程能够建立不一样的表示。 html
类型:建立类模式 编程
类图: 设计模式
四个要素 测试
代码实现 ui
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
|
class
Product
{
private
String
name
;
private
String
type
;
public
void
showProduct
(
)
{
System
.
out
.
println
(
"名称:"
+
name
)
;
System
.
out
.
println
(
"型号:"
+
type
)
;
}
public
void
setName
(
String
name
)
{
this
.
name
=
name
;
}
public
void
setType
(
String
type
)
{
this
.
type
=
type
;
}
}
abstract
class
Builder
{
public
abstract
void
setPart
(
String
arg1
,
String
arg2
)
;
public
abstract
Product
getProduct
(
)
;
}
class
ConcreteBuilder
extends
Builder
{
private
Product
product
=
new
Product
(
)
;
public
Product
getProduct
(
)
{
return
product
;
}
public
void
setPart
(
String
arg1
,
String
arg2
)
{
product
.
setName
(
arg1
)
;
product
.
setType
(
arg2
)
;
}
}
public
class
Director
{
private
Builder
builder
=
new
ConcreteBuilder
(
)
;
public
Product
getAProduct
(
)
{
builder
.
setPart
(
"宝马汽车"
,
"X7"
)
;
return
builder
.
getProduct
(
)
;
}
public
Product
getBProduct
(
)
{
builder
.
setPart
(
"奥迪汽车"
,
"Q5"
)
;
return
builder
.
getProduct
(
)
;
}
}
public
class
Client
{
public
static
void
main
(
String
[
]
args
)
{
Director
director
=
new
Director
(
)
;
Product
product1
=
director
.
getAProduct
(
)
;
product1
.
showProduct
(
)
;
Product
product2
=
director
.
getBProduct
(
)
;
product2
.
showProduct
(
)
;
}
}
|
建造者模式的优势 this
首先,建造者模式的封装性很好。使用建造者模式能够有效的封装变化,在使用建造者模式的场景中,通常产品类和建造者类是比较稳定的,所以,将主要的业务逻辑封装在导演类中对总体而言能够取得比较好的稳定性。 spa
其次,建造者模式很容易进行扩展。若是有新的需求,经过实现一个新的建造者类就能够完成,基本上不用修改以前已经测试经过的代码,所以也就不会对原有功能引入风险。 设计
建造者模式与工厂模式的区别 htm
咱们能够看到,建造者模式与工厂模式是极为类似的,整体上,建造者模式仅仅只比工厂模式多了一个“导演类”的角色。在建造者模式的类图中,假如把这个导演类看作是最终调用的客户端,那么图中剩余的部分就能够看做是一个简单的工厂模式了。 对象
与工厂模式相比,建造者模式通常用来建立更为复杂的对象,由于对象的建立过程更为复杂,所以将对象的建立过程独立出来组成一个新的类——导演类。也就是说,工厂模式是将对象的所有建立过程封装在工厂类中,由工厂类向客户端提供最终的产品;而建造者模式中,建造者类通常只提供产品类中各个组件的建造,而将具体建造过程交付给导演类。由导演类负责将各个组件按照特定的规则组建为产品,而后将组建好的产品交付给客户端。
总结
建造者模式与工厂模式相似,他们都是建造者模式,适用的场景也很类似。通常来讲,若是产品的建造很复杂,那么请用工厂模式;若是产品的建造更复杂,那么请用建造者模式。
相关参考:建造者模式