當直接實例化處在同一包結構中、實現統一接口的多個類。能夠把類的構造函數聲明爲非公共的,並經過Factory來建立它們的實例 java
(針對多個類:把多個類的構造方法先creation method,以後提取到工廠類中) 編程
public abstract class AttributeDescriptor { protected AttributeDescriptor() { } public void sayHello() { } } public class IntegerDescriptor extends AttributeDescriptor { public IntegerDescriptor() { super(); } public void sayHello() { System.out.println("I am integer method"); } } public class BooleanDescriptor extends AttributeDescriptor { public BooleanDescriptor() { super(); } public void sayHello() { System.out.println("I am boolean method"); } } public class ReferenceDescriptor extends AttributeDescriptor { public ReferenceDescriptor() { super(); } public void sayHello() { System.out.println("I am reference method"); } }
重構以後: 函數
public abstract class AttributeDescriptor { protected AttributeDescriptor(){ } public void sayHello(){ } public AttributeDescriptor forInteger(){ return new IntegerDescriptor(); } public AttributeDescriptor forBoolean(){ return new BooleanDescriptor(); } public AttributeDescriptor forReference(){ return new ReferenceDescriptor(); } } public class IntegerDescriptor extends AttributeDescriptor{ public void sayHello(){ System.out.println("I am integer method"); } } public class BooleanDescriptor extends AttributeDescriptor{ public void sayHello(){ System.out.println("I am boolean method"); } } public class ReferenceDescriptor extends AttributeDescriptor{ public void sayHello(){ System.out.println("I am reference method"); } }
AttributeDescriptor a = AttributeDescriptor.forInteger(); a.sayHello();
- 當客戶只能得到Factory的二進制代碼而沒法得到源碼時,對Factory的定製將受到限制 spa