Observer(订阅与发布)
觀察者模式:
觀察者模式很好理解,類似于郵件訂閱和RSS訂閱,當(dāng)我們?yōu)g覽一些博客或wiki時(shí),經(jīng)常會(huì)看到RSS圖標(biāo),就這的意思是,當(dāng)你訂閱了該文章,如果后續(xù)有更新,會(huì)及時(shí)通知你。其實(shí),簡單來講就一句話:當(dāng)一個(gè)對象變化時(shí),其它依賴該對象的對象都會(huì)收到通知,并且隨著變化!對象之間是一種一對多的關(guān)系。
觀察者模式:一對多的關(guān)系,當(dāng)被觀察這發(fā)生改變時(shí)會(huì)通知所有觀察者。讓雙方都依賴于抽象,使得各自變化不會(huì)影響另一方。
?
?
//發(fā)布者腳本
public class PublicObserver : MonoBehaviour {
private InputField _Title;
private InputField _Content;
private Button _publishButton;
public event System.Action<string, string> e;
private void Awake()
{
_Title = transform.Find("Title").GetComponent<InputField>();
_Content = transform.Find("Content").GetComponent<InputField>();
_publishButton= transform.Find("publishButton").GetComponent<Button>();
}
private void Start()
{
_publishButton.onClick.AddListener(EventClick);//注冊事件
}
void EventClick()
{
if (e!=null)
{
e(_Title.text, _Content.text);
}
}
}
?
?
//訂閱者腳本
public class TakeObserver : MonoBehaviour {
private Text Title;
private Text Content;
private Button _takeButton;
private Button _conentButton;
private PublicObserver actionEvent;
private void Awake()
{
Title = transform.Find("Title").GetComponent<Text>();
Content = transform.Find("Content").GetComponent<Text>();
_takeButton = transform.Find("Take").GetComponent<Button>();
_conentButton = transform.Find("Cancel").GetComponent<Button>();
if (actionEvent==null)//事件為空的找到甲苯添加事件
{
actionEvent = GameObject.Find("Publish").GetComponent<PublicObserver>();
}
}
private void Start()
{
_takeButton.onClick.AddListener(TakeEvent);
_conentButton.onClick.AddListener(ContentEvent);
}
private void TakeEvent(string title,string content)//委托調(diào)用的方法
{
Title.text = title;
Content.text = content;
}
private void TakeEvent()//訂閱
{
actionEvent.e += TakeEvent;//添加事件
}
private void ContentEvent()//取消
{
actionEvent.e -= TakeEvent;
}
}
轉(zhuǎn)載于:https://www.cnblogs.com/YangMengMeng/p/9126377.html
總結(jié)
以上是生活随笔為你收集整理的Observer(订阅与发布)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 盒子模型,top和margin-top
- 下一篇: map端join和reduce端join