Program Design: The Cat shouted, and all the mice started to escape, and the host was awakened. (C # language)
Requirements:
1. The behavior of rats and Masters Should Be passive.
2. Considering scalability, the call of a cat may cause other association effects.
Key points: 1. linkage effect. To run the code, you only need to execute the cat. cryed () method. 2. abstract the mouse and the host
Scoring standard: <1>. constructs cat, mouse, and master classes, and enables the program to run (2 points)
<2> extract abstraction from mouse and master (5 points)
<3> As long as Cat. cryed () is executed, the mouse can escape and the host will be awakened. (3 points)
Public interface observer
{
Void response (); // the response of the observer, if the mouse sees the reflection of the cat
}
Public interface subject
{
Void aimat (Observer obs); // for which observers, this refers to the object to be captured by a cat-Mouse
}
Public class mouse: Observer
{
Private string name;
Public mouse (string name, subject subj)
{
This. Name = Name;
Subj. aimat (this );
}
Public void response ()
{
Console. writeline (name + "attempt to escape! ");
}
}
Public class master: Observer
{
Public master (subject subj)
{
Subj. aimat (this );
}
Public void response ()
{
Console. writeline ("host waken! ");
}
}
Public class Cat: Subject
{
Private arraylist observers;
Public CAT ()
{
This. Observers = new arraylist ();
}
Public void aimat (Observer obs)
{
This. Observers. Add (OBS );
}
Public void cry ()
{
Console. writeline ("cat cryed! ");
Foreach (Observer OBS in this. Observers)
{
Obs. Response ();
}
}
}
Class mainclass
{
Static void main (string [] ARGs)
{
Cat cat = new CAT ();
Mouse mouse1 = new mouse ("mouse1", CAT );
Mouse mouse2 = new mouse ("mouse2", CAT );
Master = new master (CAT );
Cat. Cry ();
}
}
// Configure //---------------------------------------------------------------------------------------------
Design Method 2: Design with event -- delegate ..
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 ");
}
}
Class class1
{
Static void main (string [] ARGs)
{
Cat cat = new CAT ();
Mouse mouse1 = new mouse ("mouse1", CAT );
Mouse mouse2 = new mouse ("mouse2", CAT );
Master = new master (CAT );
Cat. Cry ();
}
}