[設計模式練習]觀察者模式
員工或者司機幫老闆開門
觀察老闆的反應
類別圖
物件檔定義
using System.Collections.Generic;
using System.Text;
namespace DesignModelTest.觀察者
{
/// <summary>
/// 被觀察者
/// </summary>
abstract class Subject
{
//要通知的觀察者
private List<Observer> observers = new List<Observer>();
/// <summary>
/// 加入觀察者.
/// </summary>
/// <param name="observer">The observer.</param>
public void Attach(Observer observer)
{
observers.Add(observer);
}
/// <summary>
/// 移除觀察者.
/// </summary>
/// <param name="observer">The observer.</param>
public void Detach(Observer observer)
{
observers.Remove(observer);
}
/// <summary>
/// 發出訊息通知觀察者做下一步動作.
/// </summary>
public void Notify()
{
foreach (Observer tmpobserver in observers)
{
tmpobserver.OpenDoor();
}
}
}
/// <summary>
/// 觀察者介面
/// </summary>
abstract class Observer
{
public abstract void OpenDoor();
}
/// <summary>
/// 被觀察的對象:老闆
/// </summary>
class Boss : Subject
{
private string _subjectState;
public string subjectState
{
get { return _subjectState; }
set { _subjectState = value; }
}
private string _name;
public string name
{
get { return _name;}
set { _name = value;}
}
}
/// <summary>
/// 觀察者:員工
/// </summary>
class Employee : Observer
{
private string name;
private Boss boss;
public Employee(Boss iniboss, string inputname)
{
boss = iniboss;
name = inputname;
}
public override void OpenDoor()
{
Console.WriteLine("員工{0}幫老闆{1}開門,老闆覺得{2}", name, boss.name, boss.subjectState);
}
}
/// <summary>
/// 觀察者:司機
/// </summary>
class Driver : Observer
{
private string name;
private Boss boss;
public Driver(Boss iniboss, string inputname)
{
boss = iniboss;
name = inputname;
}
public override void OpenDoor()
{
Console.WriteLine("司機{0}幫老闆{1}開門,老闆覺得{2}", name, boss.name, boss.subjectState);
}
}
}
用戶端程式碼
//被觀察者:老闆
DesignModelTest.觀察者.Boss boss = new DesignModelTest.觀察者.Boss();
boss.name = "阿狗";
boss.subjectState = "很屌";
//觀察者:員工小張
DesignModelTest.觀察者.Observer chang = new DesignModelTest.觀察者.Employee(boss, "小張");
//增加觀察者
boss.Attach(chang);
//發出訊息
boss.Notify();
//移除觀察者
boss.Detach(chang);
boss.name = "阿貓";
boss.subjectState = "很差";
DesignModelTest.觀察者.Observer liao = new DesignModelTest.觀察者.Driver(boss, "小廖");
boss.Attach(liao);
boss.Notify();
Console.Read();
#endregion
輸出結果