Reflection + abstract factory + configuration file

method

Use strings to instantiate objects, and variables can be replaced at any time.

Add an App.config file, read the file to assign a value to the string, and specify whether it is Sqlserver or Access in the configuration file.

 

format

Assembly.Load("Assembly Name").CreateInstance("Namespace. Class Name")

 

Specific steps

The first step is to add the App.config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>    
	<appSettings>
		<add key="DB" value="Sqlserver"/>
	</appSettings>
</configuration>

 

The second step, add a namespace

using System.Reflection;   

 

The third step, write code

User class

//用户类
class User
{
    private int _id;             //成员变量:id
    public int ID                //调用get、set方法获取修改成员变量
    {
        get { return _id; }
        set { _id = value; }
    }

    private string _name;         //成员变量:name
    public string Name            //调用get、set方法获取修改成员变量
    {
        get { return _name; }
        set { _name = value; }
    }
}

IUser interface

interface IUser
{
    void Insert(User user);
    User GetUser(int id);
}

SqlServerUser class

class SqlserverUser : IUser
{
        public void Insert(User user)         //通过传参传一条User类型的记录,往表中添加数据
        {
            Console.WriteLine("在SQL Server中给User表增加一条记录");
        }

        public User GetUser(int id)           //外部传来参数id获取表中数据
        { 
            Console.WriteLine("在SQL Server中根据ID得到User表一条记录");
            return null;
        }
}

AccessUser class

class AccessUser : IUser
{
        public void Insert(User user)           //通过传参传一条User类型的记录,往表中添加数据
        {
            Console.WriteLine("在SQL Server中给User表增加一条记录");
        }

        public User GetUser(int id)             //外部传来参数id获取表中数据
        {
            Console.WriteLine("在SQL Server中根据ID得到User表一条记录");
            return null;
        }
}

DataAccess class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;        //引入反射
using System.Configuration;     //引入配置文件

namespace 抽象工厂模式
{
    class DataAccess
    {
        private static readonly string AssemblyName = "抽象工厂模式";    //设置一个只读的静态成员变量,值为程序集的名称
        private static readonly string db = ConfigurationManager.AppSettings["DB"];  //读取配置文件,根据key值DB获取value值

        public static IUser CreateUser()       //CreateUser方法
        {
            string className = AssemblyName + "." + db + "User";        //拼接字符串
            return (IUser)Assembly.Load(AssemblyName).CreateInstance(className);  //反射,获取实例,返回具体的一个对象
        }       
    }
}

Client program code

static void Main(string[] args)
{
    User user = new User();    //实例化一个对象

    IUser iu = DataAccess.CreateUser();  //反射

    iu.Insert(user);     //向表中添加一条数据
    iu.GetUser(1);       //从表中获取一条数据

    Console.Read();
}

 

Guess you like

Origin blog.csdn.net/weixin_43319713/article/details/113698798