桥梁模式:将抽象化(Abstraction)与实现化 (Implementation)脱耦,使得二者可以独立地变化.
桥梁模式类图:
抽象化(Abstraction)角色:抽象化给出的定义,并保存 一个对实现化对象的引用。
修正抽象化(Refined Abstraction)角色:扩展抽象化角 色,改变和修正父类对抽象化的定义。
实现化(Implementor)角色:这个角色给出实现化角色的接口,但不给出具体的实现。必须指出的是,这个接口不一定和抽象化角色的接口定义相同,
实际上,这两个接口可以非常不一样。实现化角色应当只给出底层操作,而抽象化角色应当只给出基于底层操作的更高一层的操作。
具体实现化(Concrete Implementor)角色:这个角色 给出实现化角色接口的具体实现。
示例代码:
class Program { static void Main(string[] args) { Abstraction abstraction = new RefinedAbstraction(); abstraction.Implementor = new ConcreteImplementorA(); abstraction.Operation(); abstraction.Implementor = new ConcreteImplementorB(); abstraction.Operation(); Console.ReadKey(); } class Abstraction { protected Implementor implementor; public Implementor Implementor { set { implementor = value; } } virtual public void Operation() { implementor.Operation(); } } abstract class Implementor { public abstract void Operation(); } class RefinedAbstraction : Abstraction { public override void Operation() { implementor.Operation(); } } class ConcreteImplementorA : Implementor { public override void Operation() { Console.WriteLine("ConcreteImplementorA Operation"); } } class ConcreteImplementorB : Implementor { public override void Operation() { Console.WriteLine("ConcreteImpletementB Operation"); } } }