简单工厂模式(转)
简单工厂模式的实现。
假如我的程序中有需要一系列的对象,比如bed,desk,chair…, 要想利用他们,我们就必须在程序中根据用户要求,然后一个个调用 new 操作符来生成他们,这样客户程序就要知道相应的类的信息,生成的代码显然不够灵活。再此它们显然是一类的,都是furniture,既然如此,我们只要一个生产家具的工厂就可以.我们可以在代码中不利用具体的类,而只是说明我们需要什么,然后就能够得到我们想要的对象.
先定义一个类,主要声明一个家具接口,床和椅子的类:
Public interface IFurniture
{}
public class Bed:IFurniture
{
public Bed()
{
Console.WriteLine("I need a bed!");
}
}
public class Desk:IFurniture
{
public Desk()
{
Console.WriteLine("I need a desk!");
}
}
public class Chair:IFurniture
{
public Chair()
{
Console.WriteLine("I need a chair!");
}
}
{}
public class Bed:IFurniture
{
public Bed()
{
Console.WriteLine("I need a bed!");
}
}
public class Desk:IFurniture
{
public Desk()
{
Console.WriteLine("I need a desk!");
}
}
public class Chair:IFurniture
{
public Chair()
{
Console.WriteLine("I need a chair!");
}
}
再定义一个家具工厂的类(可以利用反射机制中Type类获取Name指定的类名的类的Type信息,然后可以根据这个信息利用System.Activator创建对象):
public class FurnitureFactory
{
public IFurniture MakeFurniture(string Name)
{
IFurniture MyFurniture = null;
try
{
Type type = Type.GetType(Name,true);
MyFurniture = (IFurniture)Activator.CreateInstance(type);
}
catch (TypeLoadException e)
Console.WriteLine("I dont know this kind of furniture,
exception caught - {0}" ,e.Message);
return MyFurniture;
}
}
{
public IFurniture MakeFurniture(string Name)
{
IFurniture MyFurniture = null;
try
{
Type type = Type.GetType(Name,true);
MyFurniture = (IFurniture)Activator.CreateInstance(type);
}
catch (TypeLoadException e)
Console.WriteLine("I dont know this kind of furniture,
exception caught - {0}" ,e.Message);
return MyFurniture;
}
}
然后在以客户端进行程序调用:
string FurnitureName = Console.ReadLine();
IFurniture MyFurniture;
FurnitureFactory MyFurnitureFactory = new FurnitureFactory();
MyFurniture = MyFurnitureFactory.MakeFurniture(FurnitureName);
IFurniture MyFurniture;
FurnitureFactory MyFurnitureFactory = new FurnitureFactory();
MyFurniture = MyFurnitureFactory.MakeFurniture(FurnitureName);
就这样预期想实现的,通过这样就实现了.当然这个例子比较简单,但是它却通过工厂模式的思想实现了代码的灵活性.应用软件系统开发中,有许多地方可以考 虑使用工厂模式.比如在写数据层的代码时候,考虑到程序的可移植性,可拓展性,面向不同的数据库时,采用工厂模式不为是一件理想的实现方式.