當用來實例化一個類的數據和代碼在多個類中處處都是時,能夠將有關建立的知識搬移到一個Factory中 java
(針對一個類) this
只有確實改進了代碼設計,或者沒法直接進行實例化時纔有足夠的理由進行Factory重構 設計
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 class PersonFactory { public Person createPoorPerson(String name){ return new Person(name, null, null, null); } public Person createPersonWithPhone(String name, String phone){ return new Person(name, phone, null, null); } public Person createPersonWithPhoneCar(String name, String phone, String car){ return new Person(name, phone, null, car); } public Person createRichPerson(String name, String phone, String house, String car){ return new Person(name, phone, house, car); } }