iT邦幫忙

2022 iThome 鐵人賽

DAY 19
0

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();
        }
    }
}

輸出如下
https://ithelp.ithome.com.tw/upload/images/20221003/20151894WTHDtZ15Uh.png

下篇就來說說橋接模式的實際案例

參考資料

設計模式與遊戲開發的完美結合(暢銷回饋版)


上一篇
Day 18:Observer模式(二)
下一篇
Day 20:Bridge模式(二)
系列文
如何在Unity裡寫出具有一定擴充性的遊戲30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言