由於某些類型的固有邏輯,使得它們具有兩個化的維度,乃至多個緯度的變化。
如何應對這種“多維度變化多維度變化”?如何利用面對象技術來使得類型可以輕鬆地沿著兩個乃至多個方向變化,而不引入額外的複雜度?
意圖:將一個事物中多個維度變化分離,使他們都可以獨立的變化。
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模式。