结构型设计模式之桥接模式(Bridge)

时间:2023-03-10 03:18:28
结构型设计模式之桥接模式(Bridge)

结构

结构型设计模式之桥接模式(Bridge)
意图 将抽象部分与它的实现部分分离,使它们都可以独立地变化。
适用性
  • 你不希望在抽象和它的实现部分之间有一个固定的绑定关系。例如这种情况可能是因为,在程序运行时刻实现部分应可以被选择或者切换。
  • 类的抽象以及它的实现都应该可以通过生成子类的方法加以扩充。这时B r i d g e 模式使你可以对不同的抽象接口和实现部分进行组合,并分别对它们进行扩充。
  • 对一个抽象的实现部分的修改应对客户不产生影响,即客户的代码不必重新编译。
  • (C + +)你想对客户完全隐藏抽象的实现部分。在C + +中,类的表示在类接口中是可见的。
  • 有许多类要生成。这样一种类层次结构说明你必须将一个对象分解成两个部分。R u m b a u g h 称这种类层次结构为“嵌套的普化”(nested generalizations )。
  • 你想在多个对象间共享实现(可能使用引用计数),但同时要求客户并不知道这一点。一个简单的例子便是C o p l i e n 的S t r i n g 类[ C o p 9 2 ],在这个类中多个对象可以共享同一个字符串表示(S t r i n g R e p )。
 using System;

     class Abstraction
{
protected Implementation impToUse; public void SetImplementation(Implementation i)
{
impToUse = i;
} virtual public void DumpString(string str)
{
impToUse.DoStringOp(str);
}
} class DerivedAbstraction_One : Abstraction
{
override public void DumpString(string str)
{
str += ".com";
impToUse.DoStringOp(str);
}
} class Implementation
{
public virtual void DoStringOp(string str)
{
Console.WriteLine("Standard implementation - print string as is");
Console.WriteLine("string = {0}", str);
}
} class DerivedImplementation_One : Implementation
{
override public void DoStringOp(string str)
{
Console.WriteLine("DerivedImplementation_One - don't print string");
}
} class DerivedImplementation_Two : Implementation
{
override public void DoStringOp(string str)
{
Console.WriteLine("DerivedImplementation_Two - print string twice");
Console.WriteLine("string = {0}", str);
Console.WriteLine("string = {0}", str);
}
} /// <summary>
/// Summary description for Client.
/// </summary>
public class Client
{
Abstraction SetupMyParticularAbstraction()
{
// we localize to this method the decision which abstraction and
// which implementation to use. These need to be decided
// somewhere and we do it here. All teh rest of the client
// code can work against the abstraction object.
Abstraction a = new DerivedAbstraction_One();
a.SetImplementation(new DerivedImplementation_Two());
return a;
} public static int Main(string[] args)
{
Client c = new Client();
Abstraction a = c.SetupMyParticularAbstraction(); // From here on client code thinks it is talking to the
// abstraction, and will not need to be changed as
// derived abstractions are changed. // more client code using the abstraction goes here
// . . .
a.DumpString("Clipcode"); return ;
}
}

桥接模式