public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
ClientSimple2 l1 = new ClientSimple2();
l1.Start();
}
}
#region 简单工厂
public class SimpleFactory
{
public static Car CreatCar(string car)
{
Car newCar = null;
if (car == "Benz")
{
newCar = new Benz();
}
else if (car == "BMW")
{
newCar = new BMW();
}
else if (car == "Ford")
{
newCar = new Ford();
}
return newCar;
}
}
public class ClientSimple
{
void Start()
{
//简单工厂
Car car1 = SimpleFactory.CreatCar("Benz");
car1.Dirve();
Car car2 = SimpleFactory.CreatCar("BMW");
car2.Dirve();
Car car3 = SimpleFactory.CreatCar("Ford"); ;
car3.Dirve();
}
}
public abstract class Car
{
public abstract void Dirve();
}
public class Benz : Car
{
public override void Dirve()
{
// Debug.Log("Dirve a Benz");
}
}
public class BMW : Car
{
public override void Dirve()
{
// Debug.Log("Dirve a BMW");
}
}
public class Ford : Car
{
public override void Dirve()
{
// Debug.Log("Dirve a Ford");
}
}
#endregion
#region 工厂模式
public abstract class Factory
{
public abstract Car CreatCar();
}
public class BenzFactory : Factory
{
public override Car CreatCar()
{
return new Benz();
}
}
public class BMWFactory : Factory
{
public override Car CreatCar()
{
return new BMW();
}
}
public class FordFactory : Factory
{
public override Car CreatCar()
{
return new Ford();
}
}
public class ClientSimple1
{
void Start()
{
//工厂方法
Car car1 = new BenzFactory().CreatCar();
car1.Dirve();
Car car2 = new BMWFactory().CreatCar();
car2.Dirve();
Car car3 = new FordFactory().CreatCar();
car3.Dirve();
}
}
#endregion
#region 抽象工厂
public class ReflectionSimpleFactory
{
public static Car CreatCar(string carClass)
{
//获取当前程序集
Assembly ass = Assembly.GetCallingAssembly();
//获取程序集中的类
Type t = ass.GetType("简单工厂_工厂模式_抽象工厂_反射."+carClass);
Type t4 = ass.GetType();
var x = t4.Namespace;
Type[] t1 = ass.GetTypes();
//创建类的实例对象
Car o = (Car)Activator.CreateInstance(t);
return o;
}
}
public class ClientSimple2
{
public void Start()
{
//反射+简单工厂
Car car1 = ReflectionSimpleFactory.CreatCar("Benz");
car1.Dirve();
Car car2 = ReflectionSimpleFactory.CreatCar("BMW");
car2.Dirve();
Car car3 = ReflectionSimpleFactory.CreatCar("Ford");
car3.Dirve();
}
}
#endregion
#region 反射
#endregion