設(shè)計(jì)模式之橋接模式
Intro
橋接模式(Bridge)秸仙,將抽象部分與它的實(shí)現(xiàn)部分分離,使得它們都可以獨(dú)立地變化未状。
這里說到抽象與它的實(shí)現(xiàn)分離指的是抽象類和它的派生類用來實(shí)現(xiàn)自己的對象
還有另外一種理解方式搀庶,一個(gè)類存在兩個(gè)(或多個(gè))獨(dú)立變化的維度溉卓,我們通過組合的方式,讓這兩個(gè)(或多個(gè))維度可以獨(dú)立進(jìn)行擴(kuò)展敦冬。
通過組合關(guān)系來替代繼承關(guān)系辅搬,避免繼承層次的指數(shù)級爆炸。這種理解方式非常類似于脖旱,我們之前講過的“組合優(yōu)于繼承”設(shè)計(jì)原則堪遂。
Sample
internal abstract class Implementor
{
public abstract void Operation();
}
internal class ConcreteImplementorA : Implementor
{
public override void Operation()
{
Console.WriteLine("ImplementorA Operation");
}
}
internal class ConcreteImplementorB : Implementor
{
public override void Operation()
{
Console.WriteLine("ImplementorB Operation");
}
}
internal abstract class Abstraction
{
protected Implementor Implementor;
public void SetImplementor(Implementor implementor)
{
Implementor = implementor;
}
public abstract void Operation();
}
internal class RefinedAbstraction : Abstraction
{
public override void Operation()
{
Implementor.Operation();
Console.WriteLine("Invoke in RefinedAbstraction");
}
}
Abstraction ab = new RefinedAbstraction();
ab.SetImplementor(new ConcreteImplementorA());
ab.Operation();
ab.SetImplementor(new ConcreteImplementorB());
ab.Operation();
More
王爭在他的極客專欄中以 jdbc 的實(shí)現(xiàn)舉例說明橋接模式
我覺得 ADO.NET 中也有類似的設(shè)計(jì),于是看了看 ADO.NET 的部分源碼萌庆,與君分享一下
ADO.NET 是 .NET 里類似于 JDBC 用來進(jìn)行數(shù)據(jù)庫操作一套抽象 API溶褪,
而 JDBC 里的各種 driver 是用來連接數(shù)據(jù)庫,提供數(shù)據(jù)庫操作具體實(shí)現(xiàn)的践险,.NET 與之對應(yīng)的是 DbProviderFactory
實(shí)際上竿滨,JDBC 本身就相當(dāng)于“抽象”。注意捏境,這里所說的“抽象”于游,指的并非“抽象類”或“接口”,而是跟具體的數(shù)據(jù)庫無關(guān)的垫言、被抽象出來的一套“類庫”贰剥。具體的 Driver(比如,com.mysql.jdbc.Driver)就相當(dāng)于“實(shí)現(xiàn)”筷频。注意蚌成,這里所說的“實(shí)現(xiàn)”,也并非指“接口的實(shí)現(xiàn)類”凛捏,而是跟具體數(shù)據(jù)庫相關(guān)的一套“類庫”担忧。JDBC 和 Driver 獨(dú)立開發(fā),通過對象之間的組合關(guān)系坯癣,組裝在一起瓶盛。JDBC 的所有邏輯操作,最終都委托給 Driver 來執(zhí)行示罗。
ADO.NET 提供了數(shù)據(jù)庫操作的抽象惩猫,而具體的 System.SqlClient
/Microsoft.SqlClient
/MySql.Data
提供了具體的實(shí)現(xiàn),ADO.NET 和 Driver 基本保持獨(dú)立開發(fā)蚜点,通過對象的組合關(guān)系組裝在一起轧房,ADO.NET 的具體操作交由對應(yīng)的實(shí)現(xiàn)完成。
具體實(shí)現(xiàn)細(xì)節(jié)可以參考文末的參考鏈接
Reference
- https://github.com/WeihanLi/DesignPatterns/tree/master/StructurePattern/BridgePattern
- https://referencesource.microsoft.com/#System.Data/fx/src/data/System/Data/Common/DbProviderFactoriesConfigurationHandler.cs,4ba4f3a32e06482d
- https://referencesource.microsoft.com/#System.Data/fx/src/data/System/Data/Common/DbProviderFactories.cs,54a4aed2ea64c166
- https://referencesource.microsoft.com/#System.Data/fx/src/data/System/Data/Common/DbProviderFactory.cs,daaf2f2e817b5fd8