Design mode-Viewer mode (List List Maintenance viewer)

Source: Internet
Author: User


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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.