这么多开关和电灯,如果现在在家里想换一盏水晶灯,难道要把墙抛开重新设计线路,才能装上水晶灯吗?当然不是的。开关连通电源,电线传输电源,电灯只是负责照明!各司其职,互不干扰,所以,想要换水晶灯,不必更换开关盒电线,只要更换电灯集合。同样,更换开关也是如此。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 桥接 { //电灯接口 public interface ILight { //接通电源 void electricConnected(); //照明 void light(); //断开电源 void electricClosed(); } //开关顶层类 public class BaseSwitch { //使用组合,设置ILight为内部私有属性,此为桥梁 protected ILight light; //构造方法将外部的light类型注入进来 public BaseSwitch (ILight light) { this.light = light; } //开灯方法 public void makeLight() { //打开开关,接通电源 this.light.electricConnected(); //照明 this.light.light(); //关闭开关,断开电源 this.light.electricClosed(); } } //遥控开关 public class RemoteControlSwitch :BaseSwitch { //构造方法 public RemoteControlSwitch(ILight light) : base(light) { } //使用遥控开关控制开灯 public void makeRemoteLight(int operColor) { //打开开关,接通电源 this.light.electricConnected(); //照明 this.light.light(); string color = ""; switch (operColor) { case 1: color = "暖色"; break; case 2: color = "蓝色"; break; case 3: color = "红色"; break; case 4: color = "白色"; break; } Console.WriteLine("...现在是" + color + "! "); //关闭开关,断开电源 this.light.electricClosed(); } } //白炽灯 public class IncandescentLight :ILight { //接通电源 public void electricConnected() { Console.WriteLine("白炽灯被打开了..."); } //断开电源 public void electricClosed() { Console.WriteLine("白炽灯被关闭了..."); } //照明 public void light() { Console.WriteLine("白炽灯照明!"); } } //水晶灯实现 public class CrystalLight:ILight { //接通电源 public void electricConnected() { Console.WriteLine("水晶灯被打开了..."); } //照明 public void light() { Console.WriteLine("水晶灯照明!"); } //断开电源 public void electricClosed() { Console.WriteLine("水晶灯被关闭了..."); } } class Program { static void Main(string[] args) { //白炽灯实例 ILight incandescentLight = new IncandescentLight(); //水晶灯实例 ILight crystalLight = new CrystalLight(); Console.WriteLine("-- 一般开关 --"); //一般开关 BaseSwitch switch1 = new BaseSwitch(incandescentLight); switch1.makeLight(); Console.WriteLine("\n-- 遥控开关 --"); //遥控开关 RemoteControlSwitch switch2 = new RemoteControlSwitch(crystalLight); switch2.makeRemoteLight(1); } } }
//一般开关 BaseSwitch switch1 = new BaseSwitch(incandescentLight); switch1.makeLight();修改为:
//一般开关 BaseSwitch switch1 = new BaseSwitch(crystalLight); switch1.makeLight();
原文地址:http://blog.csdn.net/ry513705618/article/details/38178579