标签:
/// <summary>
/// 通知者接口
/// </summary>
interface ISubject
{
void Attch(Observer observer);
void Detach(Observer observer);
void NotifyObserver();
string SubjectState { get; set; }
}
/// <summary>
/// 秘书类
/// </summary>
class Secretary : ISubject
{
//同事列表
private IList<Observer> observers = new List<Observer>();
private string _action;
//增加
public void Attch(Observer observer)
{
observers.Add(observer);
}
public void Detach(Observer observer)
{
observers.Remove(observer);
}
//通知
public void NotifyObserver()
{
foreach (Observer item in observers)
{
item.Update();
}
}
//前台状态
public string SubjectState
{
get { return _action; }
set { _action = value; }
}
}
abstract class Observer
{
public string _name;
public ISubject _sub;
public Observer(string name, ISubject sub)
{
this._name = name;
this._sub = sub;
}
public abstract void Update();
}
/// <summary>
/// 股票的观察者
/// </summary>
class StockObserver : Observer
{
public StockObserver(string name, ISubject sub)
: base(name, sub)
{
}
public override void Update()
{
Console.WriteLine("{0} {1} 关闭股票行情,继续工作!", this._sub.SubjectState, this._name);
}
}
/// <summary>
/// 看NBA的观察者
/// </summary>
class NBAObserver : Observer
{
public NBAObserver(string name, ISubject sub) : base(name, sub) { }
public override void Update()
{
Console.WriteLine("{0} {1} 关闭NBA直播,继续工作!", _sub.SubjectState, _name);
}
}
static void Main(string[] args)
{
//前台童子喆
Secretary tongzizhe = new Secretary();
//看股票的同事
StockObserver observer1 = new StockObserver("张三", tongzizhe);
NBAObserver observer2 = new NBAObserver("李四", tongzizhe);
//前台记下了两位同事
tongzizhe.Attch(observer1);
tongzizhe.Attch(observer2);
//张三没通知到
tongzizhe.Detach(observer1);
//发现老板回来
tongzizhe.SubjectState = "老板回来了";
tongzizhe.NotifyObserver();
Console.Read();
}
标签:
原文地址:http://www.cnblogs.com/tangge/p/5900330.html