名称 | Factory Method |
结构 | |
意图 | 定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。 |
适用性 | - 当一个类不知道它所必须创建的对象的类的时候。
- 当一个类希望由它的子类来指定它所创建的对象的时候。
- 当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。
|
|
|
namespace FactoryMethod
{
public abstract class LightFactory
{
public abstract Light CreateLight();
}
public class BulbLightFactory : LightFactory
{
public override Light CreateLight()
{
return new BulbLight();
}
}
public class TubeLightFactory : LightFactory
{
public override Light CreateLight()
{
return new TubeLight();
}
}
}
namespace FactoryMethod
{
public abstract class Light
{
public abstract void TurnOn();
public abstract void TurnOff();
}
public class BulbLight : Light
{
public override void TurnOn()
{
Console.WriteLine("Bulb Ligh is Turned on.\n");
}
public override void TurnOff()
{
Console.WriteLine("Bulb Ligh is Turned off.\n");
}
}
public class TubeLight : Light
{
public override void TurnOn()
{
Console.WriteLine("Tube Ligh is Turned on.\n");
}
public override void TurnOff()
{
Console.WriteLine("Tube Ligh is Turned off.\n");
}
}
}
namespace FactoryMethod
{
public class Client
{
public static void Main()
{
LightFactory BulbFactory = new BulbLightFactory();
LightFactory TubeFactory = new TubeLightFactory();
Light l1 = BulbFactory.CreateLight();
Light l2 = TubeFactory.CreateLight();
l1.TurnOn();
l1.TurnOff();
Console.WriteLine("===============\n");
l2.TurnOn();
l2.TurnOff();
}
}
}