观察者模式,是一种一对多的设计模式,观察者与被观察者存在着某种关系,当被观察者的状态发生转变时,观察者要求作出相应动作。从这个意义上来说,在这个一对多的设计模式中,“一”指的是被观察者,“多”指的是观察者。观察者很多时候都会要求注册到被观察者中,以便当被观察者状态改变时,观察者能够及时的得到响应。所有的观察者都只关心某一被观察者的状态,这么一来,如果有多个被观察者,事实上,观察者都只会注册到其感兴趣的部分。
典型的观察者模式,是猫叫-主人醒-贼跑,下面用观察者模式来实现这一系列动作。
首先来定义观察者的接口
1 public interface IObserver
2 {
3 void Response();
4 }
2 {
3 void Response();
4 }
再来是被观察者
1 public interface ISubject
2 {
3 void Register(IObserver observer);
4 void Unregister(IObserver observer);
5 }
2 {
3 void Register(IObserver observer);
4 void Unregister(IObserver observer);
5 }
下面是具体的角色
1 public class Master : IObserver
2 {
3 protected string name;
4
5 public Master(string name, ISubject subject)
6 {
7 this.name = name;
8 subject.Register(this);
9
10 Console.WriteLine(string.Format("{0} sleeping", name));
11 }
12
13 IObserver Members
21 }
22
23 public class Thief : IObserver
24 {
25 protected string name;
26
27 public Thief(string name, ISubject subject)
28 {
29 this.name = name;
30 subject.Register(this);
31
32 Console.WriteLine(string.Format("{0} trying to thieve", name));
33 }
34
35 IObserver Members
43 }
44
45 public class Cat : ISubject
46 {
47 protected List<IObserver> observers;
48 protected string name;
49
50 public Cat(string name)
51 {
52 this.name = name;
53 observers = new List<IObserver>();
54 }
55
56 public void Cry()
57 {
58 Console.WriteLine(string.Format("{0} cry", name));
59 foreach (IObserver item in observers)
60 {
61 item.Response();
62 }
63 }
64
65 ISubject Members
80 }
2 {
3 protected string name;
4
5 public Master(string name, ISubject subject)
6 {
7 this.name = name;
8 subject.Register(this);
9
10 Console.WriteLine(string.Format("{0} sleeping", name));
11 }
12
13 IObserver Members
21 }
22
23 public class Thief : IObserver
24 {
25 protected string name;
26
27 public Thief(string name, ISubject subject)
28 {
29 this.name = name;
30 subject.Register(this);
31
32 Console.WriteLine(string.Format("{0} trying to thieve", name));
33 }
34
35 IObserver Members
43 }
44
45 public class Cat : ISubject
46 {
47 protected List<IObserver> observers;
48 protected string name;
49
50 public Cat(string name)
51 {
52 this.name = name;
53 observers = new List<IObserver>();
54 }
55
56 public void Cry()
57 {
58 Console.WriteLine(string.Format("{0} cry", name));
59 foreach (IObserver item in observers)
60 {
61 item.Response();
62 }
63 }
64
65 ISubject Members
80 }
OK, 我们来Test一下
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 Cat cat = new Cat("Cat");
6 Master master = new Master("Master", cat);
7 Thief thief = new Thief("Thief", cat);
8
9 cat.Cry();
10 Console.ReadLine();
11 }
12 }
2 {
3 static void Main(string[] args)
4 {
5 Cat cat = new Cat("Cat");
6 Master master = new Master("Master", cat);
7 Thief thief = new Thief("Thief", cat);
8
9 cat.Cry();
10 Console.ReadLine();
11 }
12 }