|
Observer(观查者)模式:
类结构设计模式
多对一的触发机制
例子修改自《深入浅出设计模式(C#/JAVA版)》中例子
PS:此书貌似我借后没有剩了(大学城) 
例子可以描述为,四只老鼠对监视两只猫( mice miky 监视 tom m1 m2 监视 mike )
此模式重用的意义在于这段代码- Cat tom = new Cat("TOM");
- Cat mike = new Cat("mike");
- Mouse mice = new Mouse("mice",tom);
- Mouse miky = new Mouse("miky",tom);
- Mouse m1 = new Mouse("m1", mike);
- Mouse m2 = new Mouse("m2", mike);
- tom.Cry();
- mike.Run();
复制代码
C#- using System;
- using System.Collections;
- namespace VCSConsoleTest
- {
-
- public interface Observer
- {
- void Response(Cat subj);
- }
- public interface Subject
- {
- void AimAt(Observer Obs);
- }
- public class Mouse:Observer
- {
- private string name;
- // private Cat subj;
- public Mouse(string name,Subject subj)
- {
- this.name=name;
- //this.subj=subj;
- subj.AimAt(this);
- }
- public void Response(Cat subj)
- {
- Console.WriteLine(name+"看见了"+subj.name+subj.doing);
- }
- }
- public class Cat:Subject
- {
- private ArrayList observers;
- public string name;
- public string doing;
- public Cat(string name)
- {
- this.name=name;
- this.doing="doing nothing...";
- this.observers=new ArrayList();
- }
- public void AimAt(Observer obs)
- {
- this.observers.Add(obs);
- }
- public void Cry(){
- this.doing=" is crying...";
- this.brocast();
- this.doing=" after cry...";
- }
- public void Run()
- {
- this.doing = " is runnig...";
- this.brocast();
- this.doing = " after runing...";
- }
- public void brocast()
- {
- foreach (Observer obs in this.observers)
- obs.Response(this);
- }
- }
- class Client
- {
- [STAThread]
- static void Main(string[] args)
- {
- Cat tom = new Cat("TOM");
- Cat mike = new Cat("mike");
- Mouse mice = new Mouse("mice",tom);
- Mouse miky = new Mouse("miky",tom);
- Mouse m1 = new Mouse("m1", mike);
- Mouse m2 = new Mouse("m2", mike);
- tom.Cry();
- mike.Run();
- Console.Read();
- }
- }
- }
复制代码
[ 本帖最后由 iptton 于 2006-12-8 11:02 编辑 ] |
|