Observer(订阅与发布)

观察者模式:

观察者模式很好理解,类似于邮件订阅和RSS订阅,当我们浏览一些博客或wiki时,经常会看到RSS图标,就这的意思是,当你订阅了该文章,如果后续有更新,会及时通知你。其实,简单来讲就一句话:当一个对象变化时,其它依赖该对象的对象都会收到通知,并且随着变化!对象之间是一种一对多的关系。

观察者模式:一对多的关系,当被观察这发生改变时会通知所有观察者。让双方都依赖于抽象,使得各自变化不会影响另一方。

 

 

//发布者脚本

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)//委托调用的方法
{
Title.text = title;
Content.text = content;
}
private void TakeEvent()//订阅
{
actionEvent.e += TakeEvent;//添加事件
}
private void ContentEvent()//取消
{
actionEvent.e -= TakeEvent;
}
}

转载于:https://www.cnblogs.com/YangMengMeng/p/9126377.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值