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 + "received message:" + 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 ("The Child Cries");
}
public void Smile ()
{
Notify ("The Child Laughs");
}
}
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 ("Father went abroad to work.");
Child. Delobserver (Ob_father);
Child. Smile ();
Console.ReadLine ();
}
}
}
Design mode-Viewer mode (List List Maintenance viewer)