祕書類——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();
}
}
}
總結:前臺祕書類需要增加觀察者類。觀察者類需要前臺祕書類。