简单工厂模式:专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。它又称为静态工厂方法模式。它的实质是由一个工厂类根据传入的参数,动态决定应该创建哪一个产品类(这些产品类继承自一个父类或接口)的实例。简单工厂模式的创建目标,所有创建的对象都是充当这个角色的某个具体类的实例。在这个模式中,工厂类是整个模式的关键所在。它包含必要的判断逻辑,能够根据外界给定的信息,决定究竟应该创建哪个具体类的对象。用户在使用时可以直接根据工厂类去创建所需的实例,而无需了解这些对象是如何创建以及如何组织的。有利于整个软件体系结构的优化。
接口
public interface 动物
{
void 跑();
}
实现
public class 狮子
{
public void 跑()
{
-------
}
}
public class 老虎
{
public void 跑()
{
---------
}
}
。。。。。
工厂
public class 动物园
{
public static 动物 狮子()
{
return new 狮子();
}
public static 动物 老虎()
{
return new 老虎();
}
----------
}
2011.09.09 重新思考
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Design_Patterns
{
//接口 集合父类
interface Car
{
void Run();
}
public class BMW : Car
{
#region Car 成员
public void Run()
{
throw new NotImplementedException();
}
#endregion
}
public class Audi : Car
{
#region Car 成员
public void Run()
{
throw new NotImplementedException();
}
#endregion
}
public class Bentley : Car
{
#region Car 成员
public void Run()
{
throw new NotImplementedException();
}
#endregion
}
public class Benz : Car
{
#region Car 成员
public void Run()
{
throw new NotImplementedException();
}
#endregion
}
public enum CarType{BMW,Audi,Bentley,Benz};
//简单工厂 静态工厂方法 负责所有类型对象的创建,不支持无缝的新增新的类型对象的创建。(产品的种类是“不变”的,只是想隐藏产品的实例化过程和具体的产品)
//简单的项目使用
class SimpleFactory
{
public static Car GetCar(CarType ctype)
{
Car car = null;
switch (ctype)
{
case CarType.BMW:
car = new BMW();
break;
case CarType.Audi:
car = new Audi();
break;
case CarType.Bentley:
car = new Bentley();
break;
case CarType.Benz:
car = new Benz();
break;
default:
break;
}
return car;
}
}
//调用
class Test
{
Car c = SimpleFactory.GetCar(CarType.BMW);
public Test()
{
c.Run();
}
}
}