緊接着工廠方法模式的案例[http://www.cnblogs.com/adzhouyang/p/7398000.html]
當須要新增一個產品,好比新增一個Department對象時,工廠方法模式就須要修改
結構以下
html
此時,須要新增一個Department接口,以及分別用兩種數據庫訪問方式實現的具體Department對象,在抽象工廠類和具體工廠類裏,也須要新增相關的產生Department對象方法。數據庫
interface IDepartment { void Insert(Department department); Department GetDepartment(int id); } public class AccessDepartment : IDepartment { public void Insert(Department department) { Console.WriteLine("InsertAccessDepartment"); } public Department GetDepartment(int id) { Console.WriteLine("AccessDepartmentlist"); return null; } } public class SqlDepartment : IDepartment { public void Insert(Department department) { Console.WriteLine("InsertSqlDepartment"); } public Department GetDepartment(int id) { Console.WriteLine("SqlDepartmentlist"); return null; } } interface IFactory { IUser CreateUser(); //新增方法 IDepartment CreateDepartment(); } public class SqlFactory : IFactory { public IUser CreateUser() { return new SqlUser(); } public IDepartment CreateDepartment() { return new SqlDepartment(); } } public class AccessFactory : IFactory { public IUser CreateUser() { return new AccessUser(); } public IDepartment CreateDepartment() { return new AccessDepartment(); } } public static void Main(string[] args) { User user = new User(); Department dep = new Department(); IFactory factory = new AccessFactory(); IUser iu = factory.CreateUser(); iu.Insert(user); iu.GetUser(1); IDepartment ip = factory.CreateDepartment(); ip.Insert(dep); ip.GetDepartment(1); }
只有一個產品系列的時候,好比案例中只有一個User對象的時候,只須要用到工廠方法模式
當解決涉及到多個產品系列的問題,好比案例中增長了Department對象時,就須要用到抽象工廠模式
也就是抽象工廠模式是對工廠方法模式的擴展設計模式
提供一個建立一系列相關或相互依賴對象的接口,而無需指定它們具體的類。設計
優勢:只須要改變具體工廠便可使用不一樣的產品配置
缺點:增長產品系列時,須要同時改動每一個具體工廠code
本文根據《大話設計模式》整理得出htm