簡介:
橋接模式用在相同的東西在不同維度實現相同的功能。例如,數據庫適用在Windows和Linux平臺上或者遊戲跨平臺。
介紹:
橋接模式的結構包括Abstraction、RefinedAbstraction、Implementor、ConcreteImplementorA和ConcreteImplementorB。
抽象化角色(Abstraction) | 抽象類,並保存一個對實現化對象(Implementor)的引用。 |
修正抽象化角色(Refined Abstraction) | 繼承Abstraction,擴展抽象化角色以適用在不同維度的變化。 |
實現化角色(Implementor) | 抽象類,抽象維度的變化,提供維度變化的抽象接口。 |
具體實現化角色(Concrete Implementor) | 繼承Implementor,給出實現化角色的具體實現。 |
優點 | 1.把抽象(Abstraction)與實現(Implementor)解耦。 2.抽象和實現可以獨立擴展,互不影響。 3.實現華角色的細節對客戶透明。 |
缺點 | 1.增加系統複雜度。 |
特點 |
1.抽象(Abstraction)與實現(Implementor)不是繼承關係,可獨立變化。 2.實現化角色的任何改變不影響客戶端。 |
使用:
本案例是假想正方形在不同系統下畫出來所需要的操作。
//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();