第0章:簡介
工廠方法模式定義:定義一個用於創建對象的接口,讓子類決定實例化哪一個類,使一個類的實例化延遲到其子類工廠方法模式的實質:延遲到子類來選擇實現
模式圖:
待補充第1章:實踐
(1)接口類(Intf.java)
package com.mcc.core.designPattern.build.simpleFactory; /** * 接口 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-9 上午12:24 */ public interface Intf { public void someMethod(); } |
(2)實現類A(IntfImplA.java)
package com.mcc.core.designPattern.build.simpleFactory; /** * 實現類A * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-9 上午12:28 */ public class IntfImplA implements Intf { @Override public void someMethod() { System.out.println("實現類A"); } } |
(3)實現類B(IntfImplB.java)
package com.mcc.core.designPattern.build.simpleFactory; /** * 實現類B * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-9 上午12:28 */ public class IntfImplB implements Intf { @Override public void someMethod() { System.out.println("實現類B"); } } |
(4)創建器類(Creater.java)
package com.mcc.core.designPattern.build.factoryMethod; /** * 創建器,聲明工廠方法 * * 工廠方法模式定義:定義一個用於創建對象的接口,讓子類決定實例化哪一個類,使一個類的實例化延遲到其子類 * 工廠方法模式本質:延遲到子類來選擇實現 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-9 上午12:49 */ public abstract class Creater { //創建對象的工廠方法,具體由子類實現創建過程 protected abstract Intf factoryMethod(); public void otherMethod(){ System.out.println("工廠方法創建器,需子類實現創建過程"); } } |
(5)A對象工廠類(FactoryA.java)
package com.mcc.core.designPattern.build.factoryMethod; /** * A對象工廠 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-9 上午12:55 */ public class FactoryA extends Creater { @Override protected Intf factoryMethod() { //創建A對象 return new IntfImplA(); } } |
(6)B對象工廠類(FactoryB.java)
package com.mcc.core.designPattern.build.factoryMethod; /** * B對象工廠 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-9 上午12:59 */ public class FactoryB extends Creater { @Override protected Intf factoryMethod() { //創建B對象 return new IntfImplB(); } } |
(7)客戶端測試類(Client.java)
package com.mcc.core.designPattern.build.factoryMethod; /** * 客戶端測試 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-9 上午1:02 */ public class Client { public static void main(String args[]){ //生產A對象 Intf intfA = new FactoryA().factoryMethod(); intfA.someMethod(); //生產B對象 Intf intfB = new FactoryB().factoryMethod(); intfB.someMethod(); } } |