添加引用:
配置文件:
[code]<configuration><startup><supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.5\" /></startup><appSettings><add key=\"assemblyName\" value=\"AbstractFactory\"/><add key=\"nameSpaceName\" value=\"AbstractFactory\"/><add key=\"typename\" value=\"summer\"/></appSettings></configuration>
整个程序:
[code]using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Configuration;using System.Reflection;using System.Threading.Tasks;namespace AbstractFactory{//抽象产品类:季节public abstract class AbstractSeason{public abstract string When{get;}}//抽象产品类:气候public abstract class AbstractWeather{public abstract string How{ get; }}//具体产品:夏天public class Summer : AbstractSeason{private string time = \"Summer\";public override string When{get { return time; }}}//具体气候:热public class Hot : AbstractWeather{private string how = \"hot!\";public override string How{get { return how; }}}//抽象工厂类public abstract class Factory{//创建气候abstract public AbstractWeather creatWeather();//创建季节abstract public AbstractSeason creatSeason();}//具体工厂public class summer : Factory{public override AbstractSeason creatSeason(){return new Summer();}public override AbstractWeather creatWeather(){return new Hot();}}//客户端代码//创建夏天类public class CreatSummer{private AbstractSeason myseason;private AbstractWeather myweather;public CreatSummer(Factory time){myseason = time.creatSeason();myweather = time.creatWeather();}public void showTime() //显示对应季节及天气{Console.WriteLine(\"季节:{0}\", myseason.When);Console.WriteLine(\"天气:{0}\", myweather.How);Console.ReadLine();}}class Program{static void Main(string[] args){//利用配置文件管理类来读取系统配置文件,获得AppSettings节中key为FactoryName的value值//即:要使用哪个工厂子类来创建运算子类//反射技术的格式://Assembly.Load(\"程序集名称\").CreateInstance(\"命名空间.类名称\")//作用:根据 \"命名空间.类名称\"来创建该类的实例//由于CreateInstance(\"命名空间.类名称\")中的参数为字符串类型,可以写成变量,//而变量的值可从配置文件中得到//创建一个工厂类的实例//创建一个工厂类的实例string assemblyName = ConfigurationManager.AppSettings[\"assemblyName\"]; //程序集的名字string fullTypeName = string.Concat(ConfigurationManager.AppSettings[\"nameSpaceName\"], \".\", ConfigurationManager.AppSettings[\"typeName\"]); //命名空间名+类名Factory Time = (Factory)Assembly.Load(assemblyName).CreateInstance(fullTypeName);CreatSummer time = new CreatSummer(Time); //创建指定系列的衣服time.showTime(); //显示相应的信息Console.ReadLine();}}}
}