桥接模式(Bridge Pattern):将抽象部分与它的实现部分分离,使它们都可以独立地变化,它是一种对象结构型模式。
在一个软件系统的抽象部分和实现部分之间使用组合/聚合关系而不是继承关系,从而使两者可以相对独立地变化。
结构:
角色:
Abstraction角色:定义抽象类的接口,并保存一个指向Implementor类型对象的指针。
Refined Abstraction角色:扩展抽象角色。
Implementor角色:这个角色给出实现类的接口,但不给出具体的实现。实现类角色应当只给出底层操作,而抽象类角色应当只给出基于底层操作的更高一层的操作。
Concrete Implementor角色:这个角色给出实现类角色接口的具体实现。
示例代码:
using System;
// "Abstraction"
class Abstraction
{
// Fields
protected Implementor implementor;
// Properties
public Implementor Implementor
{
set{ implementor = value; }
}
// Methods
virtual public void Operation()
{
implementor.Operation();
}
}
// "Implementor"
abstract class Implementor
{
// Methods
abstract public void Operation();
}
// "RefinedAbstraction"
class RefinedAbstraction : Abstraction
{
// Methods
override public void Operation()
{
implementor.Operation();
}
}
// "ConcreteImplementorA"
class ConcreteImplementorA : Implementor
{
// Methods
override public void Operation()
{
Console.WriteLine("ConcreteImplementorA Operation");
}
}
// "ConcreteImplementorB"
class ConcreteImplementorB : Implementor
{
// Methods
override public void Operation()
{
Console.WriteLine("ConcreteImplementorB Operation");
}
}
public class Client
{
public static void Main( string[] args )
{
Abstraction abstraction = new RefinedAbstraction();
// Set implementation and call
abstraction.Implementor = new ConcreteImplementorA();
abstraction.Operation();
// Change implemention and call
abstraction.Implementor = new ConcreteImplementorB();
abstraction.Operation();
}
}
Bridge模式使用要点:
Bridge模式使用“对象间的组合关系”解耦了抽象和实现之间固有的绑定关系,使得抽象(Tank的型号)和实现(不同的平台)可以沿着各自的维度来变化。
所谓抽象和实现沿着各自维度的变化,即“子类化”它们,比如不同的Tank型号子类,和不同的平台子类)。得到各个子类之后,便可以任意组合它们,从而获得不同平台上的不同型号。
Bridge模式有时候类似于多继承方案,但是多继承方案往往违背单一职责原则(即一个类只有一个变化的原因),复用性比较差。Bridge模式是比多继承方案更好的解决方法。
有两个变化的维度,但是某个方向的变化维度并不剧烈——换言之两个变化不会导致纵横交错的结果,并不一定要使用Bridge模式。