23种设计模式----桥接模式(Bridge Pattern)
如果一个抽象类或接口有多个具体实现子类,而这些子类之中有内容或概念上重叠,需要我们把抽象的共同部分各自独立开来:即原来是准备放在一个接口里,现在需要设计两个接口——抽象接口和行为接口。然后再分别针对各自的具体子类定义抽象接口和行为接口的方法和调用关系。
桥接模式的用意是将抽象化(Abstraction)与实现化(Implementation)脱耦,使得二者可以独立地变化。
public abstract class Implementor { public abstract void Operation(); } public class ConcreteImplementorA : Implementor { public override void Operation() { Console.WriteLine("ConcreteImplementorA Operation"); } } public class ConcreteImplementorB : Implementor { public override void Operation() { Console.WriteLine("ConcreteImplementorB Operation"); } } public class Abstraction { protected Implementor implementor; public Implementor Implementor { set { implementor = value; } } public virtual void Operation() { implementor.Operation(); } } public class RefinedAbstraction : Abstraction { public override void Operation() { implementor.Operation(); } } static void Main(string[] args) { Abstraction abstraction = new RefinedAbstraction(); abstraction.Implementor = new ConcreteImplementorA(); abstraction.Operation(); abstraction.Implementor = new ConcreteImplementorB(); abstraction.Operation(); }
ConcreteImplementorA Operation
ConcreteImplementorB Operation
情形:
◊ 不希望在抽象与实现部分之间有固定的绑定关系;
◊ 类的抽象以及它的实现都应该可以通过生成子类的方法加以扩充。这时桥接模式可以对不同的抽象接口和实现部分进行组合,并分别对它们进行扩充;
◊ 对抽象的实现部分进行修改应对客户不产生影响,即客户的代码不必重新编译;
◊ 想对客户完全隐藏抽象的实现部分;
◊ 想在多个对象间共享实现,但同时要求客户并不知道这点。
特点:
◊ 分离接口及其实现部分,一个实现未必不变地绑定在一个接口上。抽象类的实现可以在运行时刻进行配置,一个对象甚至可以在运行时刻改变它的实现;
◊ 将Abstraction与Implementor分离有助于降低对实现部分编译时刻的依赖性;当改变一个实现类时,并不需要重新编译Abstraction类和Client类。为了保证一个类库的不同版本之间的兼容,需要有这个特性;
◊ 接口与实现分离有助于分层,从而产生更好的结构化系统。系统的高层部分仅需要知道Abstraction和Implementor即可;
◊ 提高可扩充性。可以独立的对Abstraction和Implementor层次结构进行扩充;
◊ 实现细节对Client透明。可以对Client隐藏实现细节,如共享Implementor对象以及相应的引用计数机制。
- 23种设计模式(7)_结构型_桥接模式(Bridge Pattern)
- 23种设计模式-6.桥接模式(Bridge Pattern)
- 【结构型模式】桥接模式(Bridge)之23种java设计模式
- 设计模式读书笔记之桥接模式(bridge pattern)
- Java23种设计模式案例:桥接模式(bridge)
- 设计模式-----桥接模式(Bridge Pattern)
- .NET设计模式(9):桥接模式(Bridge Pattern)
- 23种设计模式之桥接模式(Bridge)
- 设计模式-----桥接模式(Bridge Pattern)(转)
- 二十四种设计模式:桥接模式(Bridge Pattern)
- Net设计模式实例之桥接模式( Bridge Pattern)
- 设计模式(结构型)之桥接模式(Bridge Pattern)
- [Unity 设计模式]桥接模式(BridgePattern)
- 设计模式-----桥接模式(Bridge Pattern)
- [置顶] [Unity 设计模式]桥接模式(BridgePattern)
- 设计模式-----桥接模式(Bridge Pattern)
- C#设计模式之桥接模式(Bridge Pattern)
- 乐在其中设计模式(C#) - 桥接模式(Bridge Pattern)
- [Unity 设计模式]桥接模式(BridgePattern)
- 乐在其中设计模式(C#) - 桥接模式(Bridge Pattern)