读书笔记17:桥接模式

 概念
 将抽象部分和与之对应的实现部分分离,使它们可以独立地变化。
角色
Implementor—— 定义实现类的接口

CreateImplementorFirst(CreateImplementorSecond)——实现Implementor接口及定义其具体实现。

Abstraction——定义抽象的接口。是依据Implementor所构成的高阶操作。

RefinedAbstraction—— 扩充Abstraction。

程序实现模型
先看看,程序的实现:

Implementor

    public abstract class Implementor      {          public abstract void Operation();      }

实现Implementor

  public class CreateImplementorFirst : Implementor      {          public override void Operation()          {              Console.WriteLine("具体实现方法(1)。");          }      }        public class CreateImplementorSecond : Implementor      {          public override void Operation()          {              Console.WriteLine("具体实现方法(2)。");          }      }

Abstraction

 public class Abstraction      {          protected Implementor implementor;            public void SetImplementor(Implementor paramImplementor)          {              this.implementor = paramImplementor;          }            public virtual void Operation()          {              implementor.Operation();          }      }

RefinedAbstraction

    public class RefinedAbstraction : Abstraction      {          public override void Operation()          {              implementor.Operation();          }      }

客户端调用:

        static void Main(string[] args)          {              Abstraction abstraction = new RefinedAbstraction();                abstraction.SetImplementor(new CreateImplementorFirst());                abstraction.Operation();                abstraction.SetImplementor(new CreateImplementorSecond());                abstraction.Operation();                Console.ReadLine();          }

结果:
 

     这里乍一看,有一些工厂模式与策略模式结合的意思,Abstraction有点像工厂,CreateImplementorFirst和CreateImplementorSecond像实现不同的策略。
     实际是不同的,桥接模式应用情况是, 当一个属性可能有许多种实现时一般使用继承来处理,使用一个抽象类定义此属性的接口;再以具体类不同方式的实现。这就相当于工厂模式和策略模式结合的,但这种方式有时不方便,因为继承不容易维护、扩充及独立的再使用属性及实现。桥接模式将抽象的属性及实现放置于不同的类层级架构中以解决这个问题。Abstraction、RefinedAbstraction两个类与Implementor实现了层级架构,而Implementor子类CreateImplementorFirst,CreateImplementorSecond具体实现。

 桥接模式优点:

1. 降低属性与实现的耦合性:实现未绑在接口因此一个属性的实现可以再执行期组态(configure);甚至对象降低属性与实现的耦合性同时可以降低编译期实现的关连性。改变实现类无须重新编译Abstraction类即使用端,这是最基本的特性当你要确保不同版本类程序馆(library)可以在执行期改变其实现。的位兼容性(binary compatibility)。更甚者低耦合可以有更好的结构系统。系统高阶的部分只需知道Abstraction及Implementor。

2.提高扩充性:你可以独立的扩充Abstraction及Implementor层级架构。

3.对使用端隐藏详细的实现:你可以隐藏详细的实现;像共享的Implementor对象及伴随的参考计数机制(如果有的话)。
 

参考资料:

1、新浪博客
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值