I. Program Design: when the cat shouted, all the mice started to escape and the host was awakened.
Requirement: first, the interaction between the mouse and the host is passive. Second, considering scalability, the call of a cat may cause other linkage effects.
Answer:
1. Use inerface design:
Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Collections;
Class Program
{
Static void Main (string [] args)
{
Cat cat = new Cat ();
Mouse mouse1 = new Mouse ("mouse1", cat );
Mouse mouse2 = new Mouse ("mouse2", cat );
Master master = new Master (cat );
Cat. Cry ();
}
}
Public interface Observer
{
Void Response (); // The observer's Response. If the mouse sees the cat's Response
}
Public interface Subject
{
Void AmiAt (Observer obs); // for which observers, this refers to the object the cat wants to capture-Mouse
}
Public class Mouse: Observer
{
Private string name;
Public Mouse (string name, Subject subj)
{
This. name = name;
Subj. AmiAt (this );
}
Public void Response ()
{
Console. WriteLine (name + "run! ");
}
}
Public class Master: Observer
{
Public Master (Subject subj)
{
Subj. AmiAt (this );
}
Public void Response ()
{
Console. WriteLine ("Host waken! ");
}
}
Public class Cat: Subject
{
Private ArrayList Observers;
Public Cat ()
{
This. Observers = new ArrayList ();
}
Public void AmiAt (Observer obs)
{
This. Observers. Add (obs );
}
Public void Cry ()
{
Console. WriteLine ("Cat cryed! ");
Foreach (Observer obs in this. Observers)
{
Obs. Response ();
}
}
}
2. Design with event-delegate:
Using System;
Using System. Collections. Generic;
Using System. Text;
Class Program
{
Static void Main (string [] args)
{
Cat cat = new Cat ();
Mouse mouse1 = new Mouse ("mouse1", cat );
Mouse mouse2 = new Mouse ("mouse2", cat );
Master master = new Master (cat );
Cat. Cry ();
}
}
Public delegate void SubEventHandler ();
Public abstract class Subject
{
Public event SubEventHandler SubEvent;
Protected void FireAway ()
{
If (this. SubEvent! = Null)
{
This. SubEvent ();
}
}
}
Public class Cat: Subject
{
Public void Cry ()
{
Console. WriteLine ("cat cryed .");
This. FireAway ();
}
}
Public abstract class Observer
{
Public Observer (Subject sub)
{
Sub. SubEvent + = new SubEventHandler (Response );
}
Public abstract void Response ();
}
Public class Mouse: Observer
{
Private string name;
Public Mouse (string name, Subject sub)
: Base (sub)
{
This. name = name;
}
Public override void Response ()
{
Console. WriteLine (name + "attempt to escape! ");
}
}
Public class Master: Observer
{
Public Master (Subject sub)
: Base (sub)
{}
Public override void Response ()
{
Console. WriteLine ("host waken ");
}
}