又称为静态工厂方法(Static Factory Method)模式,属于类的创建型模式,通过它根据自变量的不同返回不同的类的实例。
简单工厂模式专门定义一个类来负责创建其它类的实例,被创建的实例通常都具有共同的父类
模式结构:
abstract class MobilePhone
{
public abstract void Call();
public abstract void SendMSG();
}
class Iphone4S : MobilePhone
{
public override void Call()
{
Console.WriteLine("用Iphone4S打电话");
}
public override void SendMSG()
{
Console.WriteLine("用Iphone4S发短信");
}
}
class GalaxyNote2 : MobilePhone
{
public override void Call()
{
Console.WriteLine("用GalaxyNote2打电话");
}
public override void SendMSG()
{
Console.WriteLine("用GalaxyNote2发短信");
}
}
class SimpleFactory
{
static MobilePhone ph;
public static MobilePhone CreatePhone(string phonename)
{
switch (phonename)
{
case "Iphone4S":
ph = new Iphone4S();
break;
case "GalaxyNote2":
ph = new GalaxyNote2();
break;
case "HTCOneM7":
ph = new HTCOneM7();
break;
default:
break;
}
return ph;
}
class Program
{
static void Main(string[] args)
{
MobilePhone ph;
ph = SimpleFactory.CreatePhone("Iphone4S");
ph.Call();
ph.SendMSG();
Console.ReadKey();
}
}