C#观察者模式

来源:互联网 发布:战舰世界 个人数据 编辑:程序博客网 时间:2024/05/23 00:31
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Blog : MonoBehaviour{
    public class ModalBase{
    public delegate void EventHanler();
    public event EventHanler Event;
    public void UpdateData(){
            this.Event ();
        }
    }

    public class Observer{
        public Observer(ModalBase modal){
            modal.Event+=new ModalBase.EventHanler(Response);
        }
        public virtual void Response(){
            
        }
    }

    public class Cat:ModalBase{
        public void Shout(){
            Debug.Log ("猫大叫");
            this.UpdateData ();
        }
    }
    public class Mouse:Observer{
        public Mouse(ModalBase modal):base(modal){

        }
        public override void Response ()
        {
            base.Response ();
            Debug.Log ("老鼠跑路");
        }
    }
    public class Man:Observer{
        public Man(ModalBase modal):base(modal){

        }
        public override void Response ()
        {
            base.Response ();
            Debug.Log ("人醒来");
        }
    }
    void Start(){
        Cat cat = new Cat ();
        Mouse mouse = new Mouse (cat);
        Man man = new Man (cat);
        cat.Shout ();
    }
}
原创粉丝点击