观察者模式

来源:互联网 发布:昆明java 编辑:程序博客网 时间:2024/06/03 20:22
using System;
using System.Collections.Generic;
using System.Collections;
using UnityEngine;
public abstract class Subject01
{
    private List<Observer01> ob = new List<Observer01>();
    public void Attach(Observer01 obser)
    {
        ob.Add(obser);
    }
    public void RemoveObj(Observer01 obser)
    {
        ob.Remove(obser);
    }
    public void Notify()
    {
        foreach (Observer01 o in ob)
        {
            o.Receive();
        }
    }

}


using System;
using System.Collections.Generic;
using System.Collections;
using UnityEngine;
 public  class MySubject:Subject01
 {
     private string subjectState;
     public string SubjectState
     {
         get { return subjectState; }
         set { subjectState = value; }
     }
 }


using System;
using System.Collections.Generic;
using System.Collections;
 public abstract  class Observer01
 {
     public abstract void Receive();
 }

using System;
using System.Collections.Generic;
using System.Collections;
using UnityEngine;
 public  class MyObserver : Observer01
 {
    private  string name;
     public MyObserver(string name)
     {
         this.name = name;
     }
     public override void Receive()
     {
         Debug.Log(name);
     }
 }


using UnityEngine;
using System.Collections;
public class MyText : MonoBehaviour {
// Use this for initialization
void Start () {
        MySubject sub = new MySubject();
        sub.Attach(new MyObserver("111"));
        sub.Attach(new MyObserver("222"));
        sub.Notify();
}

// Update is called once per frame
void Update () {

}
}



原创粉丝点击