设计模式-观察者模式(List列表维护观察者)
namespace ConsoleApplication1
{
interface IObserver
{
void ReceiveMsg(string msg);
}
class Observer : IObserver
{
string Key;
public Observer(string key)
{
this.Key = key;
}
public void ReceiveMsg(string msg)
{
Console.WriteLine("Observer-" + Key + " 收到消息:" + msg);
}
}
interface ISubject
{
void AddObserver(IObserver ob);
void DelObserver(IObserver ob);
void Notify(string msg);
}
class Subject : ISubject
{
List<IObserver> observerList = new List<IObserver>();
public void AddObserver(IObserver ob)
{
if (!observerList.Contains(ob))
observerList.Add(ob);
}
public void DelObserver(IObserver ob)
{
if (observerList.Contains(ob))
observerList.Remove (ob);
}
public void Notify(string msg)
{
foreach (IObserver ob in observerList)
{
ob.ReceiveMsg(msg);
}
}
}
class Child : Subject
{
public void Cry()
{
Notify("孩子哭了");
}
public void Smile()
{
Notify("孩子笑了");
}
}
class Program
{
static void Main(string[] args)
{
IObserver ob_father = new Observer("Father");
IObserver ob_mather = new Observer("Mather");
Child child = new Child();
child.AddObserver(ob_father);
child.AddObserver(ob_mather);
child.Cry();
Console.ReadLine();
Console.WriteLine("父亲外出国打工了..");
child.DelObserver(ob_father);
child.Smile();
Console.ReadLine();
}
}
}