设计模式-建造者模式

由于标准版的建造者模式我目前还没用过(或者见过我没认出来==),这里只说一种特殊的建造者模式,它适用于当一个类构造器需要传入很多参数时,如果使用构造函数创建这个类的实例,代码可读性会非常差,而且很容易引入错误,此时就可以利用 builder模式 :

public class Person
{

    private String eyes;

    private String nose;

    private String mouth;

    private String ears;

    private String hair;

    /**
     * @param builder
     */
    public Person(Builder builder)
    {
        this.eyes = builder.eyes;
        this.nose = builder.nose;
        this.mouth = builder.mouth;
        this.ears = builder.ears;
        this.hair = builder.hair;
    }

    @Override
    public String toString()
    {
        return "Person [eyes=" + eyes + ", nose=" + nose + ", mouth=" + mouth + ", ears=" + ears + ", hair=" + hair
                + "]";
    }

    public static final class Builder
    {
        private String eyes;

        private String nose;

        private String mouth;

        private String ears;

        private String hair;

        public Builder()
        {}

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

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

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

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

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

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

    }
}
public class Client
{
    public static void main(String[] args)
    {
        Person xiaoming = new Builder()
                .eyes("大眼睛")
                .nose("小鼻子")
                .mouth("大嘴巴")
                .ears("小耳朵")
                .hair("红头发")
                .build();
        System.out.println(xiaoming.toString());
    }
}

这样的建造者模式更加灵活,非常使用于参数很多的状况,而且我们可以在builder的每个赋值方法中对参数进行校验。如果这些操作在实体对象本身的构造函数中校验呢?想都不敢想会是什么后果。
这种形式的建造者模式最常见肯定是在netty中莫属了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值