The cat shouted, and all the mice started to escape, and the host was awakened. (C # language)
1. The behavior of rats and Masters Should Be passive.
2. Considering scalability, the call of a cat may cause other association effects.
1. Use interfaces:
Code
Public interface observer {
Void response (); // The observer's response, which is a reflection of a mouse seeing a cat
}
Public interface subject {
Void aimat (Observer obs); // for which observers, this refers to the object to be captured by a cat-Mouse
}
/// <Summary>
/// The mouse corresponds to the observed object.
/// </Summary>
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! ");
}
}
/// <Summary>
/// Corresponding to the master, inheriting the observed object
/// </Summary>
Public class master: Observer {
Public master (subject subj ){
Subj. aimat (this );
}
Public void response (){
Console. writeline ("host waken! ");
}
}
/// <Summary>
/// The role of the cat view as the observer
/// </Summary>
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 ();
}
}
2. Design with event -- delegate ..
Code
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 master = new Master(cat); cat.Cry();
}
}
From: http://kb.cnblogs.com/page/50471/