在Java开发中,Builder模式是一种强大的创建型模式,它允许我们逐步构建复杂的对象。本文将详细介绍Builder模式的意图、解释、编程示例、适用场景以及实际应用。同时,还将提供示例代码的下载链接,方便读者进行学习和实践。
Java中的Builder设计模式是一种基本的创建型模式,它允许逐步构建复杂的对象。它将复杂对象的构建与表示分离,使得相同的构建过程可以创建不同的表示。
public Hero(Profession profession,String name,HairType hairType,HairColor hairColor,Armor armor,Weapon weapon){
// 值赋值
}
- 正如你所看到的,构造函数参数的数量可能会迅速变得过多,使得理解它们的排列变得困难。此外,如果将来决定添加更多选项,这个参数列表可能会继续增长。这就是所谓的伸缩构造函数反模式。
在这个Java Builder模式示例中,我们构建了具有不同属性的不同类型的Hero
对象。
想象一个角色扮演游戏的角色生成器。最简单的选择是让计算机为你生成角色。但是,如果你更喜欢手动选择角色细节,如职业、性别、头发颜色等,角色创建就变成了一个逐步的过程,一旦完成所有选择就结束。
更合理的方法是使用Builder模式。首先,让我们考虑我们想要创建的Hero
:
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;
}
}
然后我们有Builder
:
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);
}
}
然后可以这样使用:
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());
}
程序输出:
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.
在以下情况下使用Builder模式:
Builder模式示例代码下载
通过本文的介绍,相信大家对Java中的Builder模式有了更深入的了解。在实际开发中,合理运用Builder模式可以提高代码的可读性和可维护性,同时更好地构建复杂的对象。