简介:
桥接模式的意图是将抽象部分与实现部分分离,使它们都可以独立的变化。可用在相同的组件在不同维度实现相同的功能。例如,数据库适用在Windows和Linux平台上或者游戏跨平台。
介绍:

| 优点 | 1.把抽象(Abstraction)与实现(Implementor)解耦。 2.抽象和实现可以独立扩展,互不影响。 3.实现角色的细节对客户透明。 |
| 缺点 | 1.增加系统复杂度。 |
| 特点 |
1.抽象(Abstraction)与实现(Implementor)不是继承关系,可独立变化。 2.实现化角色的任何改变不影响客户端。 |
| 抽象化角色(Abstraction) | 抽象类,并保存一个对实现化对象(Implementor)的引用。 |
| 修正抽象化角色(Refined Abstraction) | 继承Abstraction,扩展抽象化角色以适用在不同维度的变化。 |
| 实现化角色(Implementor) | 抽象类,抽象维度的变化,提供维度变化的抽象接口。 |
| 具体实现化角色(Concrete Implementor) | 继承Implementor,给出实现化角色的具体实现。 |
使用:
本案例的意思是假想正方形在不同系统下画出来所需要的操作。
//Abstraction
public abstract class Shape
{
protected Platform platform;
protected Shape(Platform platform)
{
this.platform = platform; //获取实现化角色的实例
}
public abstract void Draw();
}
//Implementor
public abstract class Platform
{
public abstract void Convert();
}
//RefinedAbstraction
public class Square : Shape
{
//调用基类的构造函数,实现化角色传入
public Square(Platform platform)
: base(platform)
{
}
public override void Draw()
{
this.platform.Convert(); //不同实现化角色的调用
}
}
//ConcreteImplementorA
public class SquareWindows : Platform
{
public override void Convert()
{
//do something
}
}
//ConcreteImplementorB
public class SquareLinux : Platform
{
public override void Convert()
{
//do something
}
}
//桥接模式调用
Platform platformWindows = new SquareWindows(); //Windows平台
Shape shapeWindows = new Square(platformWindows); //Windows平台下做画正方形的准备
shapeWindows.Draw(); //正方形
Platform platformLinux = new SquareWindows(); //Linux平台
Shape shapeLinux = new Square(platformLinux);
shapeLinux.Draw();
5546

被折叠的 条评论
为什么被折叠?



