using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class ObserverPattern : MonoBehaviour {
/// <summary>
/// 抽象观察者,定义接收通知的接口
/// </summary>
public abstract class Observer
{
public abstract void OnNotify();
}
/// <summary>
/// 抽象主题(抽象被观察者)类,内含观察者列表和实现接收各种通知
/// </summary>
public abstract class Subject
{
private List<Observer> observerList = new List<Observer>();
/// <summary>
/// 添加观察者
/// </summary>
/// <param name="observer"></param>
public void AddObserver(Observer observer)
{
observerList.Add(observer);
}
/// <summary>
/// 移除观察者
/// </summary>
/// <param name="observer"></param>
public void RemoveObserver(Observer observer)
{
observerList.Remove(observer);
}
/// <summary>
/// 推送通知
/// </summary>
public void Notify()
{
foreach (Observer o in observerList)
{
o.OnNotify();
}
}
}
/// <summary>
/// 具体主题(被观察者)类,实现要推送的主题
/// </summary>
public class Boss : Subject
{
private string _command;
public string Command
{
get { return _command; }
set { _command = value; }
}
}
/// <summary>
/// 观察者类,当接收到推送通知时,实现各个模块功能
/// </summary>
public class EmployeeA:Observer
{
private string _name;
private string _doSomething;
private Boss _boss;
public string Name
{
get { return _name; }
set { _name = value; }
}
public string DoSomething
{
get { return _doSomething; }
set { _doSomething = value; }
}
public EmployeeA(Boss boss)
{
_boss = boss;
}
public override void OnNotify()
{
if (_boss.Command == "下达命令")
{
Debug.Log("我是" + _name + "我要" + DoSomething);
}
}
}
public class EmployeeB : Observer
{
private string _name;
private string _doSomething;
private Boss _boss;
public string Name
{
get { return _name; }
set { _name = value; }
}
public string DoSomething
{
get { return _doSomething; }
set { _doSomething = value; }
}
public EmployeeB(Boss boss)
{
_boss = boss;
}
public override void OnNotify()
{
if (_boss.Command == "下达命令")
{
Debug.Log("我是" + _name + "我要" + DoSomething);
}
}
}
public class EmployeeC : Observer
{
private string _name;
private string _doSomething;
private Boss _boss;
public string Name
{
get { return _name; }
set { _name = value; }
}
public string DoSomething
{
get { return _doSomething; }
set { _doSomething = value; }
}
public EmployeeC(Boss boss)
{
_boss = boss;
}
public override void OnNotify()
{
if (_boss.Command == "下达命令")
{
Debug.Log("我是" + _name + "我要" + DoSomething);
}
}
}
void Start()
{
Boss boss = new Boss();
EmployeeA employeeA = new EmployeeA(boss);
EmployeeA employeeB = new EmployeeA(boss);
EmployeeA employeeC = new EmployeeA(boss);
employeeA.Name = "雇员A";
employeeA.DoSomething = "打扫卫生";
employeeB.Name = "雇员B";
employeeB.DoSomething = "整理货物";
employeeC.Name = "雇员C";
employeeC.DoSomething = "清算账目";
boss.AddObserver(employeeA);
boss.AddObserver(employeeB);
boss.AddObserver(employeeC);
boss.Command = "下达命令";
boss.Notify();
}
}
【C#】观察者模式案例
最新推荐文章于 2022-04-08 12:08:09 发布