Observer mode-instance

Source: Internet
Author: User

ProgramDESIGN: when the cat shouted, 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, runCodeRun 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)

 

 

Code

Using System;
Using System. collections;

Public   Interface Observer
{
Void Response (); // Observer (mouse and host)
}
Public   Interface Subject
{
Void Aimat (Observer obs ); // Observed (CAT)
}
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 =   New CAT ();
Mouse mouse1 =   New Mouse ( " Mouse1 " , CAT );
Mouse mouse2 =   New Mouse ( " Mouse2 " , CAT );
Master =   New Master (CAT );
Cat. Cry ();
Console. Read ();
}
}

 

 

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.