设计模式之建造者模式

概念

建造者模式(Builder),将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示

优点

  • 与其他创作模式相比,对构建过程有更多的控制
  • 支持逐步构造对象、推迟构造步骤或递归地运行步骤
  • 可以构造需要子对象的复杂组合的对象,最终产品与对象的组成的部分以及对象的组装过程分离开来
  • 单一职责原则,可以将复杂的构造代码与产品的业务逻辑隔分离开来

示例

创建英雄

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public final class Hero {
private final Profession profession;
private final String name;
private final HairType hairType;
private final HairColor hairColor;
private final Armor armor;
private final Weapon weapon;

private Hero(Builder builder) {
this.profession = builder.profession;
this.name = builder.name;
this.hairColor = builder.hairColor;
this.hairType = builder.hairType;
this.weapon = builder.weapon;
this.armor = builder.armor;
}
}
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
  public static class Builder {
private final Profession profession;
private final String name;
private HairType hairType;
private HairColor hairColor;
private Armor armor;
private Weapon weapon;

public Builder(Profession profession, String name) {
if (profession == null || name == null) {
throw new IllegalArgumentException("profession and name can not be null");
}
this.profession = profession;
this.name = name;
}

public Builder withHairType(HairType hairType) {
this.hairType = hairType;
return this;
}

public Builder withHairColor(HairColor hairColor) {
this.hairColor = hairColor;
return this;
}

public Builder withArmor(Armor armor) {
this.armor = armor;
return this;
}

public Builder withWeapon(Weapon weapon) {
this.weapon = weapon;
return this;
}

public Hero build() {
return new Hero(this);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  public static void main(String[] args) {

var mage = new Hero.Builder(Profession.MAGE, "Riobard")
.withHairColor(HairColor.BLACK)
.withWeapon(Weapon.DAGGER)
.build();
LOGGER.info(mage.toString());

var warrior = new Hero.Builder(Profession.WARRIOR, "Amberjill")
.withHairColor(HairColor.BLOND)
.withHairType(HairType.LONG_CURLY).withArmor(Armor.CHAIN_MAIL).withWeapon(Weapon.SWORD)
.build();
LOGGER.info(warrior.toString());

var thief = new Hero.Builder(Profession.THIEF, "Desmond")
.withHairType(HairType.BALD)
.withWeapon(Weapon.BOW)
.build();
LOGGER.info(thief.toString());
}
1
2
3
16:28:06.058 [main] INFO com.iluwatar.builder.App -- This is a mage named Riobard with black hair and wielding a dagger.
16:28:06.060 [main] INFO com.iluwatar.builder.App -- This is a warrior named Amberjill with blond long curly hair wearing chain mail and wielding a sword.
16:28:06.060 [main] INFO com.iluwatar.builder.App -- This is a thief named Desmond with bald head and wielding a bow.

什么时候使用建造者模式

  • 非常适合需要创建复杂对象的Java应用程序

  • 创建复杂对象的算法应该独立于组成对象的各个部分及其组装方式

  • 构造过程必须允许所构造的对象具有不同的表示形式

  • 当一个产品需要大量的步骤来创建,并且这些步骤需要按特定的顺序执行时,它特别有用用

注意事项

  • 由于需要创建多个新类,因此代码的总体复杂性可能会增加
  • 由于创建多个构建器对象,可能会增加内存使用

设计模式之建造者模式
http://s1mplecode.com/design-pattern/builder.html
作者
Jago
发布于
2024年12月23日
许可协议