【重構與模式】6.1用Creation Method替換構造函數

    類中有多個構造函數,所以很難決定在開發期間調用哪個。用可以說明意圖的返回對象實例的Creation Method替換構造函數。 java

作法:
一、找出經過調用類的構造函數來建立實例的那個客戶代碼。對構造函數調用應用提煉方法重構,生成一個公共、靜態的方法。這個新方法就是一個Creation Method。而後,應用搬移方法重構將Creation Method搬移到包括所選構造函數的類中。
二、找出調用所選構造函數類建立實例的全部代碼,將它們更新爲調用Creation Method。
三、若是所選構造函數連接到另外一個構造函數,應該讓Creation Method調用被連接的構造函數而不是所選構造函數。
四、對類中每一個要轉爲構建方法的構造函數重複步驟1-3。
五、若是類中的某個構造函數在類外無調用,將它改成非公共的。

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");
優勢:Creation Method沒有命名限制,能夠取一些可以清晰表達所建立的對象性質的名字。這種命名上的靈活性意味着兩個名字不一樣的Creation Method能夠接受數量和類型相同的參數。對於缺少現代開發環境的程序員來講,尋找死Creation Method代碼一般比尋找死構造函數代碼要容易,由於搜索特殊名字方法的表達式,比搜索一組構造函數中的一個,要好寫得多。
缺點:可能引入非標準得建立建立方式。若是大多數類都使用new實例化對象,而有些卻使用一個Creation Method,那麼程序員就必須瞭解每一個類的建立使怎樣完成的。
相關文章
相關標籤/搜索