桥接模式(Bridge)
桥接模式(Bridge),将抽象部分与它的实现部分分离,使它们可以独立地变化。
实现指的是抽象类和它的派生类用来实现自己的对象。
实现的方式有多种,桥接模式的思想就是把这些实现独立出来,让它们各自的变化,这样就使得每种实现的变化不会影响其他实现,从而达到应对变化的目的。
实现系统可能有多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让它们独立变化,减少它们的耦合。
桥接模式是合成/聚合原则的完美体现。
桥接模式结构图

实例

桥接模式代码结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| abstract class Implementor { public abstract void Operation(); } class ConcreteImplementorA : Implementor { public override void Operation() { } } class ConcreteImplementorB : Implementor { public override void Operation() { } } class Abstraction { protected Implementor implementor;
public void SetImplementor(Implementor implementor) { this.implementor = implementor; } public virtual void Operation() { implementor.Operation(); } } class RefinedAbstraction : Abstraction { public override void Operation() { implementor.Operation(); } }
Abstraction ab = new RefinedAbstraction();
ab.SetImplementor(new ConcreteImplementorA()); ab.Operation();
ab.SetImplementor(new ConcreteImplementorB()); ab.Operation();
|