日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Observer(订阅与发布)

發(fā)布時(shí)間:2024/4/15 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Observer(订阅与发布) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

觀察者模式:

觀察者模式很好理解,類似于郵件訂閱和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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。