反射+抽象工厂模式

这里通过一个DEMO介绍反射配合抽象工厂模式的运用。大概业务背景就是在实际业务过程中,可能要替换数据库,具体代码如下:

1、User实体类

class User
    {
        private int id;
        private string name;
        public int Id {
            get { return id; }
            set { id = value; }
        }
        public string Name {
            get { return name; }
            set { name = value; }
        }
    }
View Code

2、操作User实体的接口类

interface IUserDao
    {
         void Insert(User user);
         User GetUser(int id);
    }
View Code

3、实际数据库操作类

 class SqlServerImpl:IUserDao 
    {

        public void Insert(User user)
        {
            Console.WriteLine("向SqlServer插入用户!");
        }

        public User GetUser(int id)
        {
            Console.WriteLine("向SqlServer获取用户");
            return null;
        }
    }
View Code
class AccessImpl:IUserDao 
    {

        public void Insert(User user)
        {
            Console.WriteLine("向Access插入用户!");
        }

        public User GetUser(int id)
        {
            Console.WriteLine("向Access获取用户");
            return null;
        }
    }
View Code

4、数据库中间件

class DataAccess
    {
        private static readonly string DB = ConfigurationSettings.AppSettings["DB"];
        private static readonly string AssemblyName = "反射抽象工厂";
        public static IUserDao CreateUser()
        {
            string className = AssemblyName + "." + DB + "Impl";
            return (IUserDao)Assembly.Load(AssemblyName).CreateInstance(className);
        }

    }
View Code

5、配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
    </startup>
  <appSettings>
    <add  key ="DB" value ="Access"/>
  </appSettings>
</configuration>
View Code

6、客户端调用

IUserDao userDao = DataAccess.CreateUser();
            userDao.GetUser(1);
            userDao.Insert(new User());
View Code


使用此设计模式,可以将数据库直接通过配置文档修改替换,实现对修改关闭,对扩展开放

 

posted @ 2015-03-18 22:11  飘....  阅读(169)  评论(0编辑  收藏  举报