类中有多个构造函数,因此很难决定在开发期间调用哪一个。用能够说明意图的返回对象实例的Creation Method替换构造函数。
public class Person { private String name; private String phone; private String car; private String house; public Person(String name, String phone, String house, String car){ this.name = name; this.phone = phone; this.house = house; this.car = car; } public Person(String name){ this(name, null, null, null); } public Person(String name, String phone){ this(name, phone, null, null); } public Person(String name, String phone, String car){ this(name, phone, car, null); } }
我们在使用Person类的时候,会创建这几类人:有房有车有电话、没房有车有电话、没房没车有电话,只有电话、什么都没有的人。单单的一个Person构造函数无法表达清楚我们的这些需求。
public class Person { private String name; private String phone; private String car; private String house; private Person(String name, String phone, String house, String car){ this.name = name; this.phone = phone; this.house = house; this.car = car; } public static Person createPoorPerson(String name){ return new Person(name, null, null, null); } public static Person createPersonWithPhone(String name, String phone){ return new Person(name, phone, null, null); } public static Person createPersonWithPhoneCar(String name, String phone, String car){ return new Person(name, phone, null, car); } public static Person createRichPerson(String name, String phone, String house, String car){ return new Person(name, phone, house, car); } }
Person poor = Person.createPoorPerson("aqia"); Person rich = Person.createRichPerson("aqia", "1511510000", "house", "car");