秘书类——Secretary
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test_PublishOrSubscribe_Model
{
class Secretary
{
private IList<StockObserver> observers = new List<StockObserver>();
private string action;
public void attch(StockObserver observer)
{
observers.Add(observer);
}
public void notify()
{
foreach (StockObserver o in observers)
{
o.update();
}
}
public string SecretaryAction
{
get { return action; }
set { action = value; }
}
}
}
股票观察者
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test_PublishOrSubscribe_Model
{
class StockObserver
{
private string name;
private Secretary sub;
public StockObserver(String name,Secretary sub)
{
this.name = name;
this.sub = sub;
}
public void update()
{
Console.WriteLine("{0} {1} 关闭股票行情 继续工作!",sub.SecretaryAction,name);
}
}
}
客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test_PublishOrSubscribe_Model
{
class Program
{
static void Main(string[] args)
{
Secretary secretary = new Secretary();
StockObserver o1 = new StockObserver("强爸爸", secretary);
StockObserver o2 = new StockObserver("强爷爷", secretary);
secretary.attch(o1);
secretary.attch(o2);
secretary.SecretaryAction = "老板回来了!!!";
secretary.notify();
Console.ReadKey();
}
}
}
总结:前台秘书类需要增加观察者类。观察者类需要前台秘书类。