1,什麼是橋接模式?
using System;
using UnityEngine;
/// <summary>
/// 橋接模式
/// </summary>
public abstract class Bush
{
protected BushColor color;
public void setColor(BushColor bushColor)
{
color = bushColor;
}
public abstract void Paint ();
}
public class BigBush : Bush
{
public override void Paint()
{
Console.WriteLine("Using big brush and color {0} painting", color.color);
}
}
public class SmallBrush : Bush
{
public override void Paint()
{
Console.WriteLine("Using SmallBrush brush and color {0} painting", color.color);
}
}
public class BushColor
{
public string color;
}
public class RedBushColor : BushColor
{
public RedBushColor()
{
this.color = "Read";
}
}
public class BlueBushColor : BushColor
{
public BlueBushColor()
{
this.color = "blue";
}
}
public class YellowBushColor : BushColor
{
public YellowBushColor()
{
this.color = "yellow";
}
}
/// <summary>
/// 測試方法
/// </summary>
public class testBirdgeMain
{
Bush tesBush = new BigBush();
public void test()
{
tesBush.setColor (new RedBushColor());
tesBush.Paint ();
tesBush.setColor (new BlueBushColor());
tesBush.Paint ();
tesBush.setColor (new YellowBushColor());
tesBush.Paint ();
tesBush = new SmallBrush ();
tesBush.Paint ();
tesBush.setColor (new BlueBushColor());
tesBush.Paint ();
tesBush.setColor (new YellowBushColor());
tesBush.Paint ();
}
}
適用性: 1.如果一個系統需要在構件的抽象化角色和具體化角色之間增加更多的靈活性,避免在兩個層次之間建立靜態的聯繫。
2.設計要求實現化角色的任何改變不應當影響客戶端,或者說實現化角色的改變對客戶端是完全透明的。
3 .一個構件有多於一個的抽象化角色和實現化角色,系統需要它們之間進行動態耦合。
4 .雖然在系統中使用繼承是沒有問題的,但是由於抽象化角色和具體化角色需要獨立變化,設計要求需要獨立管理這兩者。Bridge要點:
1.Bridge模式使用“對象間的組合關係”解耦了抽象和實現之間固有的綁定關係,使得抽象和實現可以沿着各自的維度來變化。
2.所謂抽象和實現沿着各自維度的變化,即“子類化”它們,得到各個子類之後,便可以任意它們,從而獲得不同平臺上的不同型號。
3.Bridge模式有時候類似於多繼承方案,但是多繼承方案往往違背了類的單一職責原則(即一個類只有一個變化的原因),複用性比較差。Bridge模式是比多繼承方案更好的解決方法。
4.Bridge模式的應用一般在“兩個非常強的變化維度”,有時候即使有兩個變化的維度,但是某個方向的變化維度並不劇烈——換言之兩個變化不會導致縱橫交錯的結果,並不一定要使用Bridge模式。