0%

设计模式-观察者模式

定义了一种一对多的依赖关系,当一个对象的状态发生改变时,其所有依赖者都会收到通知并自动更新。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//抽象通知者
abstract class Subject
{
private IList<Observer> observers = new List<Observer>();
//增加观察者
public void Attach(Observer observer)
{
observers.Add(observer);
}
//移除观察者
public void Detach(Observer observer)
{
observers.Remove(observer);
}
//通知
public void Notify()
{
observers.Foreach(o => o.Update())
}
}
//抽象观察者
interface class IObserver
{
void Update();
}
//具体通知者
class ConcreateSubject : Subject
{
private string subjectState;
//具体被观察者的状态
public string SubjectState
{
get{return subjectState;}
set{subjectState = value}
}
}
//具体观察者
class ConcreatObserver : IObserver
{
private string name;
private string observerState;
private ConcreateSubject subject;
public ConcreatObserver(ConcreateSubject subject, string name)
{
this.subject = subject;
this.name = name;
}
public void Update()
{
observerState = subject.SubjectState;
Console.WriteLine("观察者{0}的新状态是{1}", name, observerState);
}
public ConcreateSubject Subject
{
get{return subject;}
set{subject = value;}
}
}
//Client
ConcreateSubject subject = new ConcreateSubject();l
subject.Attach(new ConcreatObserver(subject, "X"));
subject.Attach(new ConcreatObserver(subject, "Y"));
subject.Attach(new ConcreatObserver(subject, "Z"));
subject.SubjectState = "ABC";
subject.Notify();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//使用事件
//通知者接口
interface Subject
{
void Noticy();
string SubjectState
{
get;
set;
}
}
//具体通知者
class ConcreateSubject : Subject
{
public event EventHandler Update;
private string action;
public void Notify()
{
Update();
}
public string SubjectState
{
get{return action;}
set{action = value;}
}
}
//具体观察者
class ConcreatObserver1
{
private string name;
private Subject subject;
public ConcreatObserver1(Subject subject, string name)
{
this.subject = subject;
this.name = name;
}
public void Update1()
{
observerState = subject.SubjectState;
Console.WriteLine("观察者{0}的新状态是{1}", name, observerState);
}
}
class ConcreatObserver2
{
private string name;
private Subject subject;
public ConcreatObserver2(Subject subject, string name)
{
this.subject = subject;
this.name = name;
}
public void Update2()
{
observerState = subject.SubjectState;
Console.WriteLine("观察者{0}的新状态是{1}", name, observerState);
}
}
//Client
ConcreateSubject subject = new ConcreateSubject();
subject.Update += new EventHandler(new ConcreatObserver1(subject, "X").Update1());
subject.Update += new EventHandler(new ConcreatObserver2(subject, "Y").Update2());
subject.SubjectState = "ABC";
subject.Notify();