工厂模式+配置文件+反射实现数据访问程序

2022-11-30 16:51:19 浏览数 (1)

User表和Department表

代码语言:javascript复制
 class User
    {
        private int _id;
        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }

        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
    }

    class Department
    {
        private int _id;
        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }

        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
    }

IUser类(Department类相类似)

代码语言:javascript复制
 interface IUser
    {
        void Insert(User user);

        User GetUser(int id);
    }

    class SqlserverUser : IUser
    {
        public void Insert(User user)
        {
            Console.WriteLine("在SQL Server中User表增加一条记录");
        }

        public User GetUser(int id)
        {
            Console.WriteLine("在SQL Server中根据ID得到User表的一条记录");
            return null;
        }
    }

    class AccessUser : IUser
    {
        public void Insert(User user)
        {
            Console.WriteLine("在Access中User表增加一条记录");
        }

        public User GetUser(int id)
        {
            Console.WriteLine("在Access中根据ID得到User表的一条记录");
            return null;
        }
    }

DataAccess类

代码语言:javascript复制
 class DataAccess
    {
        private static readonly string AssemblyName = "抽象工厂";
        //直接写字符串获得db类型
        //private static readonly string db = "Sqlserver";
        //private static readonly string db = "Access";
        //读配置文件获得db类型
        private static readonly string db = ConfigurationManager.AppSettings["DB"];

        public static IUser CreateUser()
        {
            string className = AssemblyName   "."   db   "User";
            return (IUser)Assembly.Load(AssemblyName).CreateInstance(className);
        }

        public static IDepartment CreateDepartment()
        {
            string className = AssemblyName   "."   db   "Department";
            return (IDepartment)Assembly.Load(AssemblyName).CreateInstance(className);
        }
    }

App.config配置文件

代码语言:javascript复制
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="DB" value="Sqlserver"/>
  </appSettings>
</configuration>

客户端代码

代码语言:javascript复制
 			User user = new User();
            IUser iu = DataAccess.CreateUser();
            iu.Insert(user);
            iu.GetUser(1);

            Department dept = new Department();
            IDepartment id = DataAccess.CreateDepartment();
            id.Insert(dept);
            id.GetDepartment(1);

            Console.ReadKey();

UML图

0 人点赞