IElectricalEquipment.cs
// Interface
// Implementor 实现类接口
// 电器共性,抽象处理
public interface IElectricalEquipment
{
void PowerOn(); // Each electrical equipment can be turned on
void PowerOff(); // Each electrical equipment can be turned off
}
// 接口只包含方法、属性、事件或索引器的签名。
// 实现接口的类或结构必须实现接口定义中指定的接口成员。
Fan.cs
// ConcreteImplementor 具体实现类
// 电扇类
public class Fan : IElectricalEquipment
{
public void PowerOn()
{
Console.WriteLine("Fan is on");
}
public void PowerOff()
{
Console.WriteLine("Fan is off");
}
}
Light.cs
// ConcreteImplementor 具体实现类
// 电灯类
public class Light : IElectricalEquipment
{
public void PowerOn()
{
Console.WriteLine("Light is on");
}
public void PowerOff()
{
Console.WriteLine("Light is off");
}
}
Switch.cs
// Abstraction
// Switch 基类
// 电器开关
public class Switch
{
// Switch拥有IElectricalEquipment被封装的实例
public IElectricalEquipment equipment
{
get;
set;
}
public void On()
{
// Switch has an on button
Console.WriteLine("Switch on the equipment");
equipment.PowerOn();
}
public void Off()
{
// Switch has an off button
Console.WriteLine("Switch off the equipment");
equipment.PowerOff();
}
}
NormalSwitch.cs
// RefinedAbstraction 扩充抽象类
// 普通类型的开关
public class NormalSwitch : Switch
{
}
FancySwitch.cs
// RefinedAbstraction 扩充抽象类
// 特定类型的开关
public class FancySwitch : Switch
{
}
Main.cs
static void Main(string[] args)
{
// We have some electrical equipments, say Fan, Light etc.
// So, lets create them first.
IElectricalEquipment fan = new Fan();
IElectricalEquipment light = new Light();
// We also have some switches. Lets create them too.
Switch fancySwitch = new FancySwitch();
Switch normalSwitch = new NormalSwitch();
// Lets connect the Fan to the fancy switch
fancySwitch.equipment = fan;
// As the switch now has an equipment (Fan),
// so switching on or off should
// turn on or off the electrical equipment
fancySwitch.On(); // It should turn on the Fan.
// so, inside the On() method of Switch,
// we must turn on the electrical equipment.
// It should turn off the Fan. So, inside the On() method of
fancySwitch.Off();
// Switch, we must turn off the electrical equipment
// Now, lets plug the light to the fancy switch
fancySwitch.equipment = light;
fancySwitch.On(); // It should turn on the Light now
fancySwitch.Off(); // It should be turn off the Light now
normalSwitch .equipment = light;
normalSwitch.On(); // It should turn on the Light now
normalSwitch.Off(); // It should be turn off the Light now
}