设计模式-简单工厂模式
简单工厂模式(Simple Factory Pattern),又叫静态工厂方法模式(Static Factory Method Pattern)
简单工厂模式定义: 提供创建对象的接口,通常这些对象具有相同的类型。
对象具有相同的类型什么意思?我们不妨先来看简单工厂模式UML图
PC(个人电脑)是基类
Dell和IBM电脑继承了基类PC,他们都具有相同的类型,来自同一个基类(父类)。
如何运用呢?通常我们是这样创建对象比如Dell dell=new Dell() ,现在我们把这个过程封装到Factory中,
让Factory去帮我们完成这个创建工作。下面我们来看下具体的示例代码。
//抽象类
abstract class PC
{
private string name;
public PC(string name)
{
this.name = name;
}
public virtual string Name { get { return name; } set { name = value; } }
public abstract void Describe();
}
//Dell具体类,继承基类PC
class Dell : PC
{
public Dell(string name) : base(name)
{
}
public override void Describe()
{
System.Console.WriteLine("I am {0} personal computer", Name);
}
}
//IBM具体类,继承基类PC
class IBM : PC
{
public IBM(string name) : base(name)
{
}
public override void Describe()
{
System.Console.WriteLine("I am {0} personal computer", Name);
}
}
//工厂类,用于实例化各子类对象
class Factory
{
static PC pc;//定义基类对象
//看到面向接口编程了吧,Create方法返回的就是基类PC类型,而不是具体的Dell或IBM类
public static PC Create(string name)
{
if (name == "Dell")
pc = new Dell(name);//创建Dell对象
else if (name == "IBM")
pc = new IBM(name);//创建IBM对象
else
throw new NullReferenceException("object name error: " + name);
return pc;
}
}
具体调用代码
PC dell = Factory.Create("Dell");
//pc = Factory.Create("xxDell")//这个调用将出错
dell.Describe();
dell.Name = "OtherDell";
dell.Describe();
System.Console.WriteLine();
PC ibm = Factory.Create("IBM") ;
ibm.Describe();
ibm.Name = "OtherIBM";
ibm.Describe();
正确的调用方式
PC dell = Factory.Create(“Dell”);
这样调用将出错
pc = Factory.Create(“xxDell”)
简单工厂模式
优点:使用时不需要创建对象,统一由工厂创建。
缺点:必须知道要创建的具体对象的名称。
版权所有,转载请注明文章出处 http://blog/csdn.net/cadenzasolo