设计模式之建造者模式
对象多个属性,但实例化只用部分属性,减少构造器个数
实例:实例化一个 21 岁的 王五 和 一个 22 岁的 数学老师
class Teacher{ private String name; private Integer id; private String teach; static class TechersBuilt{ private String name; private Integer id; private String teach; public TechersBuilt setName(String name) { this.name = name; return this; } public TechersBuilt setId(Integer id) { this.id = id; return this; } public TechersBuilt setTeach(String teach) { this.teach = teach; return this; } public Teacher TechersBuilt(){ return new Teacher(this); } } public Teacher(TechersBuilt techersBuilt){ this.name = techersBuilt.name; this.id = techersBuilt.id; this.teach = techersBuilt.teach; } public String getName() { return name; } public Integer getId() { return id; } public String getTeach() { return teach; } } public class TeacherBuilder { public static void main(String[] args) { Teacher t1 = new Teacher.TechersBuilt().setId(21).setName("王五").TechersBuilt(); Teacher t2 = new Teacher.TechersBuilt().setId(22).setTeach("数学").TechersBuilt(); System.out.println(t1.getName()); } }