重学设计模式(三)—— 构造器模式

在实际开发过程中,我们一般通过构造方法将参数传入一般的实体类,而且实体类的构造方法可能不止一个,当参数个数过多时,伴随而来的是构造方法数量的上升,过多的构造方法参数往往给用户带来一种不明就里的感觉。

构造器模式的出现很好的解决了多参数初始化的问题。假设我们需要编写一个Student类,此类含有四个属性,代码如下:

public class Student {
    private String id;
    private String name;
    private int age;
    private Date birth;

    public Student(String id){
        this(id,null,0,null);
    }

    public Student(String id, String name){
        this(id,name,0,null);
    }

    public Student(String id, String name, int age){
        this(id,name,age,null);
    }

    public Student(String id, String name, int age, Date birth){
        this.id = id;
        this.name = name;
        this.age = age<0?0:age;
        this.birth = birth;
    }
}

该类针对不同个数的参数提供了四个构造方法,当我们需要创建对象时,我们可能会这么写

Student student = new Student("100000011","Alex",18);

看似简洁明了,但是很难说清楚每个参数的含义,不易于理解。

那我们换一种思路,对象不是通过new创建的,而是通过一种类似set的方法链的方式来设置的,最后返回一个Student对象。

public class Student {
    private String id;
    private String name;
    private int age;
    private Date birth;

    public Student(String id){
        this(id,null,0,null);
    }

    public Student(String id, String name){
        this(id,name,0,null);
    }

    public Student(String id, String name, int age){
        this(id,name,age,null);
    }

    public Student(String id, String name, int age, Date birth){
        this.id = id;
        this.name = name;
        this.age = age<0?0:age;
        this.birth = birth;
    }

    public Student(Student student){
        this.id = student.id;
        this.name = student.name;
        this.age = student.age;
        this.birth = student.birth;
    }

    public static class Builder{
        private Student target;

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

        public Builder name(String name){
            target.name = name;
            return this;
        }
        public Builder age(int age){
            target.age = age;
            return this;
        }
        public Builder birth(Date birth){
            target.birth = birth;
            return this;
        }

        public Student build() {
            return new Student(target);
        }
    }
}

这时我们可以使用如下方式创建对象

Student student = new Student.Builder().id("10000011").name("Alex").age(18).birth(new Date()).build();

构造器模式将构造器的setter方法名取成类似注释的方式,这样我们可以很清晰的知道刚才究竟设置的什么值,可读性较高,缺点是比较冗长。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值