GoF定義
將抽象與實作分離,讓他們之間的變化獨立
在這次的範例中,會以怎麼讓三種形狀的物件擁有染上相對應顏色的程式作為例子。在這邊我們將渲染顏色的功能抽象化成IColorEditor
,同時讓IShape
的介面擁有可以接收不同顏色的IColorEditor
subclass的能力。
IShape.cs
namespace LinXuan.DesignPattern.Example.Bridge
{
public abstract class IShape
{
protected IColorEditor m_ColorEditor = null;
public void SetColorEditor(IColorEditor colorEditor)
{
m_ColorEditor = colorEditor;
}
public abstract void Draw();
}
}
Shapes.cs
namespace LinXuan.DesignPattern.Example.Bridge
{
public class Sphere : IShape
{
public override void Draw()
{
m_ColorEditor.DrawColor("Sphere");
}
}
public class Cube : IShape
{
public override void Draw()
{
m_ColorEditor.DrawColor("Cube");
}
}
public class Cylinder : IShape
{
public override void Draw()
{
m_ColorEditor.DrawColor("Cylinder");
}
}
}
ColorEditor.cs
using UnityEngine;
namespace LinXuan.DesignPattern.Example.Bridge
{
public interface IColorEditor
{
public void DrawColor(string shapeName);
}
public class RedShape : IColorEditor
{
public void DrawColor(string shapeName)
{
Debug.Log("Red " + shapeName);
}
}
public class BlueShape : IColorEditor
{
public void DrawColor(string shapeName)
{
Debug.Log("Blue " + shapeName);
}
}
}
BridgeTest.cs
using UnityEngine;
namespace LinXuan.DesignPattern.Example.Bridge
{
public class BridgeTest : MonoBehaviour
{
private void Start()
{
IColorEditor redColorEditor = new RedShape();
IColorEditor blueColorEditor = new BlueShape();
IShape cube = new Cube();
IShape cylinder = new Cylinder();
IShape sphere = new Sphere();
cube.SetColorEditor(redColorEditor);
cube.Draw();
cube.SetColorEditor(blueColorEditor);
cube.Draw();
cylinder.SetColorEditor(redColorEditor);
cylinder.Draw();
cylinder.SetColorEditor(blueColorEditor);
cylinder.Draw();
sphere.SetColorEditor(redColorEditor);
sphere.Draw();
sphere.SetColorEditor(blueColorEditor);
sphere.Draw();
}
}
}
輸出如下
下篇就來說說橋接模式的實際案例