您的位置:首页 > 编程语言

简单工厂模式,抽象工厂模式,反射工厂模式的代码总结

2010-01-11 17:05 453 查看

1:简单工厂模式:其作用是实例化对象而不需要客户了解这个对象属于那个具体的子类。

using System;
using System.Collections;

public class MyClass
{
public static void Main()
{
//通过参数来实例化子类。
IVehicle vehicle = FactoryVehicle.CreateVehicle("car");
vehicle.go();
Console.ReadLine();
}

}

public class FactoryVehicle
{
public static IVehicle CreateVehicle(string VehicleName)
{
switch(VehicleName.ToLower())
{
case "car":
return new Car();
case "boat":
return new Boat();
default:
return new Car();

}
}

}
public interface IVehicle
{
void go();
}
public class Car:IVehicle
{
public void go()
{
Console.WriteLine("car");
}
}
public class Boat:IVehicle
{
public void go()
{
Console.WriteLine("boat");
}
}

2:抽象工厂:即将工厂方法也抽象出来,由具体的子类来实例化工厂。产品创建部分和简单工厂模式相同。

using System;
using System.Collections;

public class MyClass
{
public static void Main()
{
//通过定义的工厂来实例化。弊端是当产品很多时需要增加很多的工厂。代码重复。
FactoryVehicle factory = new FactoryCar();
IVehicle vehicle = factory.CreateVehicle();
vehicle.go();
Console.ReadLine();
}

}

public interface FactoryVehicle
{
IVehicle CreateVehicle();

}

public class FactoryCar:FactoryVehicle
{
public IVehicle CreateVehicle()
{
return new Car();
}
}

public class FactoryBoat:FactoryVehicle
{
public IVehicle CreateVehicle()
{
return new Boat();
}
}

public interface IVehicle
{
void go();
}

public class Car:IVehicle
{
public void go()
{
Console.WriteLine("car");
}
}

public class Boat:IVehicle
{
public void go()
{
Console.WriteLine("boat");
}
}

3:反射工厂模式: 其实就是通过反射的方式来获得具体实例化是那个类。

using System;
using System.Collections;
using System.Reflection;

public class MyClass
{
public static void Main()
{
//使用反射的方法获得实例化的类
IVehicle vechicle = ReflectFactory.CreateVehicleByReflect("Car");
vechicle.go();
Console.ReadLine();

}

}

public class ReflectFactory
{
public static IVehicle CreateVehicleByReflect(string typeName)
{
Type type = Type.GetType(typeName);
ConstructorInfo ci = type.GetConstructor(System.Type.EmptyTypes);;
return (IVehicle)ci.Invoke(null);
}
}
public class FactoryBoat:FactoryVehicle
{
public IVehicle CreateVehicle()
{
return new Boat();
}
}

public class FactoryCar:FactoryVehicle
{
public IVehicle CreateVehicle()
{
return new Car();
}
}

public interface FactoryVehicle
{
IVehicle CreateVehicle();

}
public interface IVehicle
{
void go();
}

public class Car:IVehicle
{
public void go()
{
Console.WriteLine("car");
}
}

public class Boat:IVehicle
{
public void go()
{
Console.WriteLine("boat");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: