工厂方法模式是类的创建模式,其用意是定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类中。
抽象工厂角色:任何在模式中创建的对象的工厂类必须实现这个接口。
具体工厂角色:这是实现抽象工厂接口的具体工厂类。
抽象产品角色:工厂方法模式所创建的对象的超类型,也就是产品对象的共同父类或共同拥有的接口。
具体产品角色:这个角色实现了抽象产品角色所定义的接口。
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Generic;
using System.Text;
namespace Simple_Factory
{
/// <summary>
/// 抽象类
/// </summary>
public abstract class Light
{
public abstract void TurnOn();
{
/// <summary>
/// 抽象类
/// </summary>
public abstract class Light
{
public abstract void TurnOn();
public abstract void TurnOff();
}
}
/// <summary>
/// 具体类1
/// </summary>
public class BulbLight:Light
{
public override void TurnOn()
{
Console.WriteLine("Bulb Light is Turned on");
}
/// 具体类1
/// </summary>
public class BulbLight:Light
{
public override void TurnOn()
{
Console.WriteLine("Bulb Light is Turned on");
}
public override void TurnOff()
{
Console.WriteLine("Bulb Light is Turned off");
}
}
{
Console.WriteLine("Bulb Light is Turned off");
}
}
/// <summary>
/// 具体类2
/// </summary>
public class TubeLight:Light
{
public override void TurnOn()
{
Console.WriteLine("Tube Light is Turned on");
}
/// 具体类2
/// </summary>
public class TubeLight:Light
{
public override void TurnOn()
{
Console.WriteLine("Tube Light is Turned on");
}
public override void TurnOff()
{
Console.WriteLine("Tube Light is Turned off");
}
}
{
Console.WriteLine("Tube Light is Turned off");
}
}
/// <summary>
/// 抽象工厂类
/// </summary>
public abstract class Creator
{
public abstract Light factroy();
}
/// 抽象工厂类
/// </summary>
public abstract class Creator
{
public abstract Light factroy();
}
/// <summary>
/// 具体工厂类1
/// </summary>
public class BulbCreator : Creator
{
public override Light factroy()
{
return new BulbLight();
}
}
/// 具体工厂类1
/// </summary>
public class BulbCreator : Creator
{
public override Light factroy()
{
return new BulbLight();
}
}
/// <summary>
/// 具体工厂类2
/// </summary>
public class TubeCreator : Creator
{
public override Light factroy()
{
return new TubeLight();
}
}
/// 具体工厂类2
/// </summary>
public class TubeCreator : Creator
{
public override Light factroy()
{
return new TubeLight();
}
}
/// <summary>
/// 客户端
/// </summary>
class Factory_Method
{
Creator c1 = new BulbCreator();
Light l1 = c1.factory();
l1.TurnOn();
l1.TurnOff();
}
}
/// 客户端
/// </summary>
class Factory_Method
{
Creator c1 = new BulbCreator();
Light l1 = c1.factory();
l1.TurnOn();
l1.TurnOff();
}
}
该模式便于扩展,如果想扩展只需要添加一个实体类和一个实体工厂即可。