C# design patterns: reflection and configuration files

C# design pattern: reflection + configuration file of abstract factory pattern

reflection

It is a way to get objects without passing new.
Use character strings to instantiate objects, and variables can be replaced, eliminating the trouble of switch judgment.

The first is the code structure diagram of reflection + abstract factory (data access program):

Can be compared with the code structure diagram of the abstract factory pattern

We can find that: DataAccess class uses reflection technology to replace IFactory, SqlSeverFactory, AccessFactory

So how do you write reflection?

The following is a comparison of the code:

//常规的写法
IUser result= new SqlseverUser();
//反射的写法
using System.Reflection ;
//先引用System.Reflection的命名空间
IUser result = (IUser) Assembly .Load ("当前'程序集'的名称").CreateInstance ("当前'命名空间'名称.SqlseverUser")
//SqlseverUser是要实例化的类名 

The specific code of the abstract factory pattern in the big talk design pattern is:

using System.Reflection ;//引入反射
            class DataAccess
            {
                private static readonly string AssemblyName = "抽象工厂模式";//程序集名称
                private static readonly string db = "Sqlserver";//数据库名称,可替换
                
                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);
                }

If we need to increase Oracle data access, then we only need to change one sentence of code:

IUser result = (IUser) Assembly .Load ("当前'程序集'的名称").CreateInstance ("当前'命名空间'名称".OracleUser);

Of course, when changing the database access, we need to change the program (change the value of the db string), and you can use the configuration file to solve the problem of changing the DataAccess.

The blog summary of this configuration file is very comprehensive: https://blog.csdn.net/lovelion/article/details/7430414

What is a configuration file:

The XML document is the configuration file, which is used to store the class name of a specific class. Here we only need to add a configuration file in XML format.

The configuration file is written in the U layer:

code show as below:

<?xml version="1.0"  encoding="utf-8" ?>

<configuration>

   <appSettings>

     <add key="DB" value="Sqlserver"/>
    //在此添加我们需要的key 与value

   </appSettings>

</configuration>

Read configuration file

//在程序开头添加引用
using System.Configuration
private static readonly string db = ConfigurationManager.AppSetting["DB"]

 

Guess you like

Origin blog.csdn.net/weixin_44690047/article/details/109543704