來說說Unity觀察者(Observer)模式

何爲觀察者模式,大家都比較形象的例子,和報紙的訂閱差不多,訂閱者就屬於觀察者,我想要訂閱報紙了,然後就像報刊社訂閱報紙,然後每天都有郵遞員向您這送報紙,不想訂閱了,就自己取消,然後第二天就不會有人給你送報紙。我們來利用Delegate實現一個簡單的觀察着模式.

創建一個消息封裝體Class,用來傳遞需要的消息

using System;
using UnityEngine;

namespace UniEventDispatcher{

	//時間分發着
	public class Notification
	{	
		public GameObject m_sender;
		public object m_param;

		public Notification (GameObject  sender,object param)
		{
			m_sender = sender;
			m_param = param;
		}
		public Notification (object param)
		{
			m_sender = null;
			m_param = param;
		}

		public string getSring()
		{
			return string.Format("sender = {0},param = {1}",m_sender,m_param);
		}
	}
}
創建一個單例的主題。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace UniEventDispatcher{

	public class NotificationCenter
	{	

		///<summary>
		///定義事件分發委託
		///</summary>
		public delegate void onNotificaton(Notification notific);
		public onNotificaton  m_onNotificaton;

		public void Notice(Notification notific)
		{
			if(m_onNotificaton != null)
			{
				m_onNotificaton (notific);
			}
		}
		///<summary>
		///通知單例中心
		///</summary>
		private static NotificationCenter instance = null;
		public static NotificationCenter Get()
		{
			if(instance == null)
			{
				instance = new NotificationCenter ();
				return instance;
			}
			return instance;
		}
			
	}
}
	

我們來創建一個觀察者腳本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniEventDispatcher;

public class ObserverObjects : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
		NotificationCenter.Get ().m_onNotificaton += changeColor;
	}

	void changeColor(Notification  notification)
	{
		Debug.Log ("notification:getParam() : "+ notification.getSring());
		GetComponent< Renderer> ().material.color = (Color)notification.m_param;
	}
	
	// Update is called once per frame
	void Update () {

	}

	void OnDestory()
	{
		NotificationCenter.Get ().m_onNotificaton -= changeColor;
	}
}
創建一個發佈者腳本

using System;
using UnityEngine;
using UnityEngine.UI;
using UniEventDispatcher;

public  class SubjectObjects :  MonoBehaviour
{

	public Slider m_SliderA;
	public Slider m_SliderB;
	public Slider m_SliderC;

	void Start()
	{	
		m_SliderA = GameObject.FindWithTag ("SliderA").GetComponent<Slider> ();
		m_SliderB = GameObject.FindWithTag ("SliderB").GetComponent<Slider> ();
		m_SliderC = GameObject.FindWithTag ("SliderC").GetComponent<Slider> ();

		m_SliderA.onValueChanged.AddListener(onChangeColor);
		m_SliderB.onValueChanged.AddListener(onChangeColor);
		m_SliderC.onValueChanged.AddListener(onChangeColor);
	}

	public void onChangeColor(float f)
	{
		float r = m_SliderA.value;
		float g = m_SliderB.value;
		float b = m_SliderC.value;

		//發佈消息
		NotificationCenter.Get ().Notice (new Notification(new Color (r, g, b)));
	}
}

3,創建如下的圖




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章