❶ 怎樣使用Java實現Factory設計模式
小弟不才,希望藉此篇文章,讓大蝦們共同努力,整理出一份較為完整且容易理解的用Java實現的設計模式源碼! /** * Design Pattern In Java * Name:Factory * 目的:利用工廠模式創建兩個產品系列Mac和Win * Mac:MacRam,MacCpu * Win:WinRam,WinCpu * A:abstract * C:Concret * Author:blackphoenix * Modify Date:2002-08-17 */ /** * 抽象產品類 Ram Cpu */ abstract class AProctRam { public String getProct() { return this+" Proct"; } } abstract class AProctCpu { public String getProct() { return this+" Proct"; } } /** * 具體產品 MacRam,WinRam */ class CProctMacRam extends AProctRam { public String toString() { return "MacRam"; } } class CProctWinRam extends AProctRam { public String toString() { return "WinRam"; } } /** * 具體產品 MacCpu,WinCpu */ class CProctMacCpu extends AProctCpu { public String toString() { return "MacCpu"; } } class CProctWinCpu extends AProctCpu { public String toString() { return "WinCpu"; } } /** *生成一種新的產品系列時,介面改動的代碼 */ /* class CProctNewRam extends AProctRam { public String toString() { return "NewRam"; } } class CProctNewCpu extends AProctCpu { public String toString() { return "NewCpu"; } } */ /** * 抽象工廠 AFactory */ interface AFactory { public AProctRam CreateProctRam(); public AProctCpu CreateProctCpu(); } /** * 具體工廠 CFactoryMac * 創建Mac產品系列 × MacRam MacCpu */ class CFactoryMac implements AFactory { public AProctRam CreateProctRam() { return new CProctMacRam(); } public AProctCpu CreateProctCpu() { return new CProctMacCpu(); } } /** * 具體工廠 CFactoryWin * 創建Win產品系列 × WinRam WinCpu */ class CFactoryWin implements AFactory { public AProctRam CreateProctRam() { return new CProctWinRam(); } public AProctCpu CreateProctCpu() { return new CProctWinCpu(); } } /** * 要生成一種新的產品系列時,對客戶要派發一個新的產品工廠 * 同時要派生出一種新的具體產品 * CFactoryNew * NewMem,NewCpu */ /* class CFactoryNew implements AFactory { public AProctRam CreateProctRam() { return new CProctNewRam(); } public AProctCpu CreateProctCpu() { return new CProctNewCpu(); } } */ /** * 客戶端 * 1.使用FactoryMac創建Mac系列產品:ProctMacRam,ProctMacCpu × 2.使用FactoryWin創建Win系列產品:ProctWinRam,ProctWinCpu * 3.只要知道CFactoryMac,CFactoryWin(具體工廠)和 * AProctRam,AProctCpu(抽象產品)即可,至於具體產品的創建 * 細節客戶不用關心 */ class Factory { private static void printProct(String v) { System.out.println(v); } public static void main(String[] args) { AProctRam ProctMacRam=null,ProctWinRam=null; AProctCpu ProctMacCpu=null,ProctWinCpu=null; CFactoryMac FactoryMac=new CFactoryMac(); CFactoryWin FactoryWin=new CFactoryWin(); ProctMacRam=FactoryMac.CreateProctRam(); ProctMacCpu=FactoryMac.CreateProctCpu(); ProctWinRam=FactoryWin.CreateProctRam(); ProctWinCpu=FactoryWin.CreateProctCpu(); printProct(ProctMacRam.getProct()); printProct(ProctMacCpu.getProct()); printProct(ProctWinRam.getProct()); printProct(ProctWinCpu.getProct()); /** *生成一種新的產品系列時,客戶端改動的代碼 */ /* AProctRam ProctNewRam=null; AProctCpu ProctNewCpu=null; CFactoryNew FactoryNew=new CFactoryNew(); ProctNewRam=FactoryNew.CreateProctRam(); ProctNewCpu=FactoryNew.CreateProctCpu(); printProct(ProctNewRam.getProct()); printProct(ProctNewCpu.getProct()); */ } }