當一個層次中的類都類似的實現一個方法,只是對象建立的步驟不一樣時,能夠建立調用Factory Method來處理實例化方法的惟一超類版本 java
(把子類的相似方法改爲相同的而後提取到超類裏面) ide
public class Bike { private Bike bike; public void dajiangyou(){ bike = new Bike(); System.out.println("騎自行車打醬油去"); } } public class Car { private Car car; public void dajiangyou(){ car = new Car(); System.out.println("開車打醬油去"); } }
重構後: spa
public class NewCar extends TransportFactory{ public NewCar(){ System.out.println("drive car"); } @Override protected TransportFactory create() { return new NewCar(); } } public class NewBike extends TransportFactory{ public NewBike(){ System.out.println("take bike"); } @Override protected TransportFactory create() { return new NewBike(); } } public abstract class TransportFactory { protected TransportFactory transport; protected abstract TransportFactory create(); public void dajiangyou(){ transport = create(); System.out.println("打醬油去"); } }
public static void main(String[] args) { TransportFactory t = new NewCar(); t.dajiangyou(); }
動機: code