/// <summary>
/// 工厂模式
/// 工厂模式是将对象的创建与上游使用方,进行分离。通过factory对象来创建。
/// 通过factory对象来创建,通过配置信息,进行创建对象,就是工厂根据采购清单生产商品一样
/// 1.通过配置文件来配置对象信息。
/// 2.通过配置信息+反射来进行对象的创建。
/// 3.上游对象不需要关心对象的创建过程。
/// </summary>
class Program
{
static void Main(string[] args)
{
///1.直接创建对象方式
///对象创建在上游[主程序]已经确定,不能进行分离。
InitMethods1();
///2.通过工厂对象创建对象
InitFactory();
Console.Read();
}
private static void InitFactory()
{
IAnimal animal = ObjectFactory.CreateInit<IAnimal>();
animal.Sleep();
}
private static void InitMethods1()
{
IAnimal cat = new Cat();
IAnimal dog = new Dog();
cat.Sleep();
dog.Sleep();
}
}
创建动物(IAnimal)接口:
public interface IAnimal
{
void Sleep();
}
创建猫类(Cat),继承IAnimal
public class Cat : IAnimal
{
public void Sleep()
{
Console.WriteLine("当前对象{0}",this.GetType());
}
}
创建dog类,继承Ianimal
public class Dog : IAnimal
{
public void Sleep()
{
Console.WriteLine("当前对象{0}",this.GetType());
}
}
ObjectFactry对象,用于根据XML配置信息创建对象
class ObjectFactory
{
/// <summary>
/// 通过工厂对象创建对象
/// </summary>
/// <returns>当前实例对象</returns>
static string config = ConfigurationManager.ConnectionStrings["factoryConfig"].ConnectionString;
public static T CreateInit<T>()
{
try
{
string dllName = config.Split(',')[0];
string className = config.Split(',')[1];
Assembly assembly = Assembly.Load(dllName);
Type type = assembly.GetType(className);
return (T) Activator.CreateInstance(type);
}
catch (Exception)
{
throw new Exception("Class Exception");
}
}
}
XML:
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
<connectionStrings>
<add name="factoryConfig" connectionString="FactoryLibrary,Factory.Cat"/>
<add name="factoryConfig1" connectionString="FactoryLibrary,Factory.Dog"/>
<!---->
</connectionStrings>
</configuration>
运行结果如下图:
如果将XML配置文件修改为<add name="factoryConfig" connectionString="FactoryLibrary,Factory.Dog"/>,运行结果如下: