构建者(Builder)模式

1.意图

将复杂对象的构造与其表示分开,使得相同的构造过程可以创建不同的表示。

2.解释
  • 允许您创建不同风格的对象,同时避免构造器污染。 当有可能有几种口味的对象时很有用。 或者当创建对象时涉及很多步骤。

  • 构建器模式是一种对象创建软件设计模式,其目的是找到伸缩构造器反模式的解决方案。

3.使用场景
  • 用于创建复杂对象的算法应该独立于构成对象的部件以及它们的组合方
  • 构造过程必须允许构建的对象的不同表示
4.代码实例
public class Hero {

    private final String profession;

    private final String name;

    private final String weapon;

    private final String hairType;

    private final String hairColor;

    private Hero(Builder builder) {
        this.profession = builder.profession;
        this.name = builder.name;
        this.hairColor = builder.hairColor;
        this.hairType = builder.hairType;
        this.weapon = builder.weapon;
    }

    public static class Builder {
        private final String profession;

        private final String name;

        private String weapon;

        private String hairType;

        private String hairColor;

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

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

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

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

        public Hero build() {
            return new Hero(this);
        }
    }

    @Override
    public String toString() {
        return "Hero{" +
                "profession='" + profession + '\'' +
                ", name='" + name + '\'' +
                ", weapon='" + weapon + '\'' +
                ", hairType='" + hairType + '\'' +
                ", hairColor='" + hairColor + '\'' +
                '}';
    }
}
public class App {

    private static final Logger logger = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {
        Hero hero = new Hero.Builder("Jack", "Riobard").withHairColor("Black").build();
        logger.info(hero.toString());
    }
}

参考教程:https://github.com/iluwatar/java-design-patterns/tree/master/builder

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值