【设计模式】Bridge

前言

Bridge设计模式,将一个复杂类分成可以单独开发的部分。分成的两个部分,abstraction,implementation。字面上是抽象和实现,但不同于抽象方法及其实现。下面摘录Wiki的两句话。

decouple an abstraction from its implementation so that the two can vary independently

这句话,讲的是这个模式的定义。Bridge将abstraction从implementation中抽取出来,让abstraction和implementation这两个部分可以单独的变化。

The class itself can be thought of as the abstraction and what the class can do as the implementation.

这句话太精髓了!复杂类究竟该怎么分成两个部分?这句话给出了回答。一部分是我们看这个类应该是怎么样子的,另一部分是它可以做什么。

例子

下面改一改来自[1]的回答。

When:

         ----Animal----
         /            
      Dog              Cat
    /               /     
RunDog  SleepDog RunDog SleepDog

Refactor to:

        ----Animal----                    Behavior
        /                                 /   
Dog(Behavior)   Cat(Behavior)           Run   Sleep

应用场景

  1. 当需要运行时更改implementation的时候。和Strategy类似,但是这两个模式所解决的问题是不一样的。
  2. 当一个类的变化处在两个维度,一个类违反了单一职责原则的时候。

总结

这篇博客太水了。

参考

  1. https://stackoverflow.com/questions/319728/when-do-you-use-the-bridge-pattern-how-is-it-different-from-adapter-pattern
  2. https://en.wikipedia.org/wiki/Bridge_pattern
原文地址:https://www.cnblogs.com/zzk0/p/11246446.html