设计模式实例-抽象工厂模式

using System;
namespace Ahoo.Demo.DesignPatterns.Patterns.AbstractFactory
{
    /*######抽象工厂模式####### * 提供创建一系列相关/项目依赖对象的接口, * 无需指定具体子类。 */
    public class Department { }
    interface IDepartmentDAL
    {
        void Insert(Department entity);
        Department GetEntity(long Id);
    }
    /// <summary>
    /// 3....
    /// </summary>
    public class SqlServerDepartment : IDepartmentDAL
    {
        public void Insert(Department entity)
        {
            Console.WriteLine("在MS-SQL中插入一条Department记录!");
        }
        public Department GetEntity(long Id)
        {
            Console.WriteLine("在MS-SQL中获得一条Department记录!");
            return new Department();
        }
    }
    public class MySqlDepartment : IDepartmentDAL
    {
        public void Insert(Department entity)
        {
            Console.WriteLine("在MySql中插入一条Department记录!");
        }
        public Department GetEntity(long Id)
        {
            Console.WriteLine("在MySql中获得一条Department记录!");
            return new Department();
        }
    }
    /// <summary>
    /// 1....
    /// 抽象工厂接口,包含所有产品创建的抽象方法
    /// </summary>
    interface IFactory
    {
        IDepartmentDAL CreateDepartmentDAL();
        //IUserDAL CreateUserDAL();
    }

    /// <summary>
    /// 2....
    /// 具体实现工厂
    /// </summary>
    public class SqlServerFactory : IFactory
    {
        public IDepartmentDAL CreateDepartmentDAL()
        {
            return new SqlServerDepartment();
        }
    }

    public class Client
    {
        public static void Excute()
        {
            IFactory factory = new SqlServerFactory();
            IDepartmentDAL dal = factory.CreateDepartmentDAL();
            dal.Insert(new Department { });
        }
    }

    /// <summary>
    /// 反射技术的改善
    /// </summary>
    public class DataAccess
    {
        private static readonly string AssemblyName = "抽象工厂模式";
        private static readonly string DB = "SqlServer";
        public static IDepartmentDAL CreateDepartmentDal()
        {
            string className = String.Format("{0}.{1}.{2}", AssemblyName, DB, "DepartmentDAL");
            IDepartmentDAL dal = (IDepartmentDAL)Assembly.Load(AssemblyName).CreateInstance(className);
            return dal;
        }
    }
}

你可能感兴趣的:(设计模式,抽象工厂模式)