C#物件導向設計模式學習筆記(7) – Bridge 橋接模式(結構型模式)

來源:互聯網
上載者:User

由於某些類型的固有邏輯,使得它們具有兩個化的維度,乃至多個緯度的變化。

如何應對這種“多維度變化多維度變化”?如何利用面對象技術來使得類型可以輕鬆地沿著兩個乃至多個方向變化,而不引入額外的複雜度?

意圖:將一個事物中多個維度變化分離,使他們都可以獨立的變化。       

 

 

public abstract class Tank
{
protected TankPlatformImplementation tankImpl;

public void SetImpl(TankPlatformImplementation tankImpl)
{
this.tankImpl = tankImpl;
}

public abstract void Shot();
}

public class T50 : Tank
{
public override void Shot()
{
tankImpl.DoShot();
}
}
public class PCT50 : T50 { }
public class MobileT50 : T50 { }

 

public class T75 : Tank
{
public override void Shot()
{
tankImpl.DoShot();
}
}
public class PCT75 : T75 { }
public class MobileT75 : T75 { }

 

public abstract class TankPlatformImplementation
{
public abstract void DoShot();
}
public class PCTankPlatformImplementation : TankPlatformImplementation
{
public override void DoShot()
{
Console.WriteLine("PC:DoShot");
}
}
public class MobileTankPlatformImplementation : TankPlatformImplementation
{
public override void DoShot()
{
Console.WriteLine("Mobile:DoShot");
}
}

 

public class App
{
public static void Main()
{
//手機版的Tank
T50 tank = new T50();
tank.SetImpl(new MobileTankPlatformImplementation());
tank.Shot();

//PC版的Tank
T50 tank = new T50();
tank.SetImpl(new PCTankPlatformImplementation());
tank.Shot();
}
}

 

Bridge的幾個要點:

1、Bridge模式使用“對象間的組合關係”解耦了抽象和實現之間固有的綁定關係,使得抽象和實現可以沿著各自的維度來變化;

2、所謂抽象和實現沿著各自緯度的變化,即“子類化”它們;

3、Bridge模式有時候類似於多繼承方案,但是多繼承方案往往違背單一職責原則往往違背單一職責原則(即一個類只有一個變化的原因),複用性比較差,Bridge模式是比多繼承方案更好的解決方案;

4、Bridge模式的應用一般在“兩個非常強的變化維度”,有時即使有兩個變更維度,但是某個方向的變化維度並不劇烈——換言之兩個變化不會導致縱橫交錯的結果,並不一定要使用Bridge模式。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.