定义definition:Decouple an abstraction from its implementation so that the two can vary independently. 分离抽象与其实现以使他们能够独立的变化。
Participants
The classes and/or objects participating in this pattern are:
Abstraction (BusinessObject)
Defines the abstraction's interface.
Maintains a reference to an object of type Implementor.
RefinedAbstraction (CustomersBusinessObject)
Extends the interface defined by Abstraction.
Implementor (DataObject)
Defines the interface for implementation classes. This interface doesn't have to correspond exactly to Abstraction's interface; in fact the two interfaces can be quite different. Typically the Implementation interface provides only primitive operations, and Abstraction defines higher-level operations based on these primitives.
ConcreteImplementor (CustomersDataObject)
Implements the Implementor interface and defines its concrete implementation.
sample code in C#
This structural code demonstrates the Bridge pattern which separates (decouples) the interface from its implementation. The implementation can evolve without changing clients which use the abstraction of the object.
This real-world code demonstrates the Bridge pattern in which a BusinessObject abstraction is decoupled from the implementation in DataObject. The DataObject implementations can evolve dynamically without changing any clients.
// Bridge pattern -- Real World example
using System; using System.Collections;
namespace DoFactory.GangOfFour.Bridge.RealWorld {
// MainApp test application
class MainApp { staticvoid Main() { // Create RefinedAbstraction Customers customers = new Customers("Chicago");
// Set ConcreteImplementor customers.Data = new CustomersData();
publicoverridevoid ShowAllRecords() { foreach (string name in customers) { Console.WriteLine(" " + name); } } } }
Output
Jim Jones
Samual
Jackson
Allen Good
------------------------
Customer Group:
Chicago
Jim Jones
Samual
Jackson
Allen Good
Ann Stills
Lisa Giolani
Henry Velasquez
------------------------
看着UML class diagram和上面的code,理解bridge不是很困难,不过好像也没多大感觉哦。说实在的,缺乏实际经验,不是很理解为什么要这么做。不过有一点是肯定的,那就是这个模式的好处就是抽象和实现都可以变化。Abstraction用有一个implementor的实例对象,然后基类这一层的是这样子的,Abstraction拥有一个函数operation,此函数体执行的是implementor的函数OperationImp。这样子的话,我们就可以通过继承implementor来获得concrete implementor,然后Abstraction的operation执行的就是concrete implmentor的OperationImp了。此时,就是一个有点变形的Adapter模式了,不信的话你去看UML class diagram。这个时候,我们的Abstraction也要变化了!sigh,要变得东西真多啊,呵呵。所以我们又对Abstraction进行继承、泛化得到RefinedAbstraction。此时,我们不必改operation函数就可以保证我们这边的改变不会影响到implementor那一块的代码了。还是很不错的。恩。Over。