观察者模式:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
缺点:有时需要更新部分细节,但此模式必须更新观察者的所有细节,导致不必要的时间消耗。
实际中应该根据应用场景,权衡使用观察者模式或者广播事件模式。
public class test : MonoBehaviour
{
// Use this for initialization
void Awake()
{
Boss chen = new Boss();
StockObserver stocker = new StockObserver("jack", chen);
NBAObserver NBAer = new NBAObserver("nba", chen);
chen.Update += new Boss.EventHandler(stocker.CloseStockMarket);
chen.Update += new Boss.EventHandler(NBAer.CloseNBATV);
chen.SubjectState = " chen boss is comming";
chen.Notify();
}
}
//看股票的同事
class StockObserver
{
private string name;
private Subject sub;
public StockObserver(string name ,Subject sub)
{
this.name = name;
this.sub = sub;
}
public void CloseStockMarket()
{
Debug.Log(string.Format("{0} {1} 关闭股票行情,继续工作", sub.SubjectState, name));
}
}
//看NBA的同事
class NBAObserver
{
private string name;
private Subject sub;
public NBAObserver(string name, Subject sub)
{
this.name = name;
this.sub = sub;
}
public void CloseNBATV()
{
Debug.Log(string.Format("{0} {1} 关闭NBA直播,继续工作", sub.SubjectState, name));
}
}
//通知者接口
interface Subject
{
void Notify();
string SubjectState { get; set; }
}
class Boss : Subject
{
public string SubjectState { get; set; }
private string action;
public delegate void EventHandler();
public event EventHandler Update;
public void Notify()
{
Update();
}
}