1.特点:当工厂方法无法满足多系列问题时,再重构为抽象工厂。
2.概念:抽象工厂模式为一个产品家族提供了统一的创建接口。当需要这个产品家族的某一系列的时候,可以从抽象工厂中选出相对应的系列来创建一个具体的工厂类别。
3.类图:
4.程序实现:
/// <summary> /// 抽象工厂类 /// </summary> public interface IDatabaseFactory { IEmployee CreateEmployee(); IUser CreateUser(); } /// <summary> /// 与SqlServer相关产品的实现 /// </summary> public class SqlServerDatabaseFactory : IDatabaseFactory { public IEmployee CreateEmployee() { return new SqlEmployee(); } public IUser CreateUser() { return new SqlUser(); } } /// <summary> /// 与Access相关产品的实现 /// </summary> public class AccessDatabaseFactory : IDatabaseFactory { public IEmployee CreateEmployee() { return new AccessEmployee(); } public IUser CreateUser() { return new AccessUser(); } } /// <summary> /// 抽象产品 /// </summary> public interface IUser { User GetUser(); bool SaveUser(); } /// <summary> /// 抽象产品 /// </summary> public interface IEmployee { Employee GetEmployee(); bool SaveEmployee(); } /// <summary> /// 与SqlServer相关的具体产品User /// </summary> public class SqlUser : IUser { public User GetUser() { return null; } public bool SaveUser() { return false; } } /// <summary> /// 与SqlServer相关的具体产品Employee /// </summary> public class SqlEmployee : IEmployee { public SqlEmployee() { } public Employee GetEmployee() { return null; } public bool SaveEmployee() { return false; } } /// <summary> /// 与Access相关的具体产品User /// </summary> public class AccessUser : IUser { public AccessUser() { } public User GetUser() { return null; } public bool SaveUser() { return false; } } /// <summary> /// 与Access相关的具体产品Employee /// </summary> public class AccessEmployee : IEmployee { public AccessEmployee() { } public Employee GetEmployee() { return null; } public bool SaveEmployee() { return false; } }
时间: 2024-10-10 01:06:03