利用反射实现工厂模式.
//ICar.dllusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ICar
{
public interface ICar
{
string GetCar();
}
}
//FuTe.dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FuTe
{
public class FuTe : ICar.ICar
{
public string GetCar()
{
return "FuTe";
}
}
}
//CarFactory.dll
using System;
using System.Reflection;
namespace CarFactory
{
public class CarFactory
{
public static ICar.ICar CreateCar(string CarFileName)
{
var CarAssembly = Assembly.LoadFrom(CarFileName);
ICar.ICar CarType = null;
foreach (var tmpCarType in CarAssembly.GetTypes())
{
CarType = (ICar.ICar)Activator.CreateInstance(tmpCarType);
break;
}
return CarType;
}
}
}
//ConsoleApplication6.exe
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
var myCar = CarFactory.CarFactory.CreateCar(@"FuTe.dll");
var CarName = myCar.GetCar();
Console.WriteLine(CarName);
Console.ReadLine();
}
}
}
如果CarFactory.CarFactory.CreateCar(这里是相对路径,那么请把ConsoleApplication6.exe和所有dll放在同一个文件夹)
此例子简单,我觉得足以表达思想.
有不明白请提问.