zoukankan      html  css  js  c++  java
  • Bridge Pattern (桥接模式)

    What exactly does it mean?                                                                   

    The Bridge pattern is an application of the old advice, "prefer composition over inheritance".It becomes handy when you must subclass different times in ways that are orthogonal with one another. Say you must implement a hierarchy of colored shapes. You wouldn't subclass Shape with Rectangle and Circle and then subclass Rectangle with RedRectangle, BlueRectangle and GreenRectangle and the same for Circle, would you? 

    You would prefer to say that each Shape has a Colorand to implement a hierarchy of colors, and that is the Bridge Pattern.

    对上面的阐述可以这样理解,对于Colored Shape,其实是有两个维度的变化,一个是Color,一个是Shape,如果要在一个继承中实现这两个维度的变化,势必会产生诸如RedRectangle之类的类,虽然这也符合关闭原则,但有以下缺点

    1. 破坏了类的单一责任原则,RedRectangle既要负责形状,又要负责颜色

    2. 代码难以复用,比如RedRectangle 和 RedCircle 中都需要Red,但是这个Red很难被复用

    解决之道就是用组合替代继承,用has a 替代 is a,这样Color 和 Shape 就可以独立变化了。 所以使用桥接模式的关键就在于观察类中是否有不同维度的变化,如果有,将这些变化抽象出来,用组合的方式进行关联。



    一个典型的应用:

    Graphical User Interface Frameworks

    Graphical User Interface Frameworks use the bridge pattern to separate abstractions from platform specific implementation. For example GUI frameworks separate a Window abstraction from a Window implementation for Linux or Mac OS using the bridge pattern.



    意图:
       将抽象部分与实现部分分离,使它们都可以独立的变化。——《设计模式》GOF 
    结构图:


    优点:

    • Decoupling interface and implementation. An implementation is not bound permanently to an interface. The implementation of an abstraction can be configured and even switched at run-time.
    • Abstraction and Implementor hierarchies can be extended independently.

    Refrence: 

    http://www.oodesign.com/bridge-pattern.html

    http://stackoverflow.com/questions/319728/when-do-you-use-the-bridge-pattern

    http://en.wikipedia.org/wiki/Bridge_pattern


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    页面性能:如何系统地优化页面?
    为什么CSS动画比JavaScript高效?
    Code Review
    浏览器中的页面之CSS是如何影响到渲染流程的
    async / await
    手撸Promise
    Promise
    宏任务和微任务
    有点恶心,随手写点儿
    关于判断用户输入的是不是int类型,这次没有正则表达式
  • 原文地址:https://www.cnblogs.com/significantfrank/p/4875835.html
Copyright © 2011-2022 走看看