Bridge Pattern (桥接模式)

简介: What exactly does it mean?                                                                    The Bridge pattern is an application of the old advice, "prefer composition over inheritance".It be

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


目录
相关文章
|
设计模式 关系型数据库
设计模式11 - 桥梁模式【Bridge Pattern】
设计模式11 - 桥梁模式【Bridge Pattern】
42 0
|
设计模式 开发者
桥接模式(Bridge Pattern)
桥接模式(Bridge Pattern)是一种结构型设计模式,它将抽象部分和实现部分分离开来,使它们可以独立地变化。
135 2
|
设计模式 Java
Java设计模式-桥接模式(Bridge Pattern)
Java设计模式-桥接模式(Bridge Pattern)
|
Linux Windows
结构型模式 - 桥接模式(Bridge Pattern)
结构型模式 - 桥接模式(Bridge Pattern)
|
设计模式 Java 数据库连接
桥接模式(Bridge Pattern)
桥接模式是一种结构型设计模式, 可将一个大类或一系列紧密相关的类拆分为抽象和实现两个独立的层次结构, 从而能在开发时分别使用。
128 0
桥接模式(Bridge Pattern)