抽象工场一般都是用反射获取配置文件想要切换的目标(概念不多说,网上一大堆重复概念),本例中用Factory类来实现(以目标数据库为例):
1,首先定义共用接口(各种目标类都要实现的)
interface IDB { void DataBase(); }
2,实现类(目标实现类都继承共用接口):
class MSSQL : IDB { public void DataBase() { Console.Write("MSSQL"); } }
class ORACLE:IDB { public void DataBase() { Console.Write("ORACLE"); } }
3,Factory类
class Factory { public static IDB CreateDb() { var assemblyName = Assembly.GetExecutingAssembly().GetName().Name; //程序集名 var db = ConfigurationManager.AppSettings["DB"]; var className = assemblyName + "." + db; //类名 return (IDB)Assembly.Load(assemblyName).CreateInstance(className); } } //(IDB)Assembly.Load("程序集名称").CreateInstance("命名空间.类名称");
4,客服端:
class Program { static void Main(string[] args) { IDB db = Factory.CreateDb(); db.DataBase(); Console.Read(); } }
5,一般抽象工场都是用app.config或者是web.config文件来切换目标的
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="DB" value="ORACLE"/> </appSettings> </configuration>
原文地址:http://www.cnblogs.com/objectboy/p/3857391.html