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

猜你喜欢

转载自www.cnblogs.com/YangMengMeng/p/9126377.html