引言
用一个电视遥控器的例子来引出桥接模式解决的问题。我们每个牌子的电视机都有一个遥控器,此时我们能想到的一个设计是——把遥控器作为一个抽象类,抽象类中提供遥控器的所有实现,其他具体电视品牌的遥控器都继承这个抽象类。这样的实现使得每部不同型号的电视机都有自己的遥控器实现。这样的设计对于电视机的改变可以很好的应对,只需要添加一个派生类就好,但随着时间的推移,用户需要改变遥控器的功能,此时就需要修改抽象类提供的接口了,此时可能只需要向抽象类中添加一个方法就可以解决,但是这样带来的问题是我们改变了抽象的实现,如果用户需要同时改变电视机型号和遥控器功能是,上面的设计就会导致相当大的修改。使用桥接模式可以解决这样的问题。
桥接模式的详细介绍
定义
桥接模式即将抽象部分与实现部分脱耦,使它们独立化。根据面向对象的封装变化原则,我们可以把实现部分的变化(遥控器功能的变化)封装到另外一个类中去,这样的思路就是桥接模式的实现。
实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _24BridgePatternDemo
{
/// <summary>
/// 测试类
/// </summary>
class Program
{
static void Main(string[] args)
{
//创建一个遥控器
RemoteControl remotecontrol = new RemoteControl();
//长虹
remotecontrol.Implementor = new Changhong();
remotecontrol.On();
remotecontrol.SetChannel();
remotecontrol.Off();
Console.WriteLine();
//三星
remotecontrol.Implementor = new Sanxing();
remotecontrol.On();
remotecontrol.SetChannel();
remotecontrol.Off();
Console.WriteLine();
ConcreteRemoter Conremotecontrol = new ConcreteRemoter();
Conremotecontrol.Implementor = new Changhong();
Conremotecontrol.On();
Conremotecontrol.Se