在了解之前,先假设有一个问题,我们需要创建一个学生对象,属性有name,age,sex,birth等属性,如果每一个属性都可以为空,也就是说我们可以只用一个name,也可以用一个age,name,或者一个name,age,sex,birth,或者其他任意的赋值来创建一个学生对象,这时该怎么构造?
难道我们写4个1个输入的构造函数,6个2个输入的构造函数.......吗?这个时候就需要用到Builder模式。
package com.example.myeureka; import java.util.Date; /** * 〈一句话功能简述〉<br> * 建造者模式 * @author DING WEI * @create 2019/1/25 10:21:21 * @since 1.0.0 */ public class TestBuild { static class Student{ private String name; private int age; private String sex; private Date birth; static class StudentBuild{ private String name; private int age; private String sex; private Date birth; public StudentBuild setName(String name){ this.name = name; return this; } public StudentBuild setAge(int age){ this.age = age; return this; } public StudentBuild setSex(String sex){ this.sex = sex; return this; } public StudentBuild setBirth(Date birth){ this.birth = birth; return this; } public Student build(){ return new Student(this); } } public Student(StudentBuild studentBuild){ this.name = studentBuild.name; this.age = studentBuild.age; this.sex = studentBuild.sex; this.birth = studentBuild.birth; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + ", birth=" + birth + '}'; } } public static void main(String[] args) { Student girl = new Student.StudentBuild().setName("阎婆惜").setAge(40).setSex("女").build(); System.out.println(girl.toString()); Student body = new Student.StudentBuild().setBirth(new Date()).setName("宋江").setSex("男").build(); System.out.println(body); } }
执行main方法,输出结果为:
Student{name='阎婆惜', age=40, sex='女', birth=null}
Student{name='宋江', age=0, sex='男', birth=Fri Jan 25 10:35:41 CST 2019}