观察者模式(C#实现)
首先实现两个接口:Subject(用于发布信息) Observer(信息接受者)
Subject中:
registerObserver(Observer observer); 用于登记需要推送的用户
removeObserver(Observer observer); 将用户剔除出推送列表
notifyObserver(); 推送服务
Observer中:
update(string news); 当Subject信息发送时,用于更新
然后用 Newsstand类和Commenpeolpe类分别实现Subject,Observer
____________________________________________________________________________________实现如下
1 public interface Subject
2 {
3 void registerObserver(Observer observer);
4 void removeObserver(Observer observer);
5 void notifyObserver();
6 }
----------------------------------------------------------------------
1 public interface Observer
2 {
3 void update(string news);
4 }
----------------------------------------------------------------------------
1 public class Newsstand:Subject
2 {
3 private string newsOfToday; //用于推送的消息
4 private ArrayList observerList = null;//定义数组,储存观察者对象
5 public Newsstand()
6 {
7 observerList = new ArrayList();
8 }
9 public void registerObserver(Observer observer)
10 {
11 observerList.Add(observer);
12 }
13
14 public void removeObserver(Observer observer)
15 {
16 if (this.observerList.IndexOf(observer) != 0)
17 observerList.Remove(observer);
18 }
19
20 public void notifyObserver()//当消息更新时自动发送给观察者
21 {
22 for (int i = 0; i < observerList.ToArray().Length; i++)
23 {
24 Observer observer =(Observer) observerList[i];
25 observer.update(this.newsOfToday);
26 }
27 }
28 public void newsChanged()
29 {
30 notifyObserver();
31 }
32 public void setNews(string news)//得到消息,处理更新
33 {
34 this.newsOfToday = news;
35 newsChanged();
36 }
37 }
-----------------------------------------------------------------------------------------------------------
1 public class Commonpeople:Observer
2 {
3 private Subject newsstand;
4 private string newsFromNewsStand;
5 public Commonpeople() { }
6 public Commonpeople(Subject newsstand)//使用上下文中的信息发布者初始化时
7 {
8 this.newsstand = newsstand;
9 this.newsstand.registerObserver(this);
10 }
11 public void update(string news)//自动取得更新数据
12 {
13 this.newsFromNewsStand = news;
14 display();
15 }
16 private void display()
17 {
18 Console.WriteLine(this.newsFromNewsStand);
19 }
20 }
------------------------------------------------------------------------------
1 static void Main(string[] args)//主程序
2 {
3 Newsstand newsStand = new Newsstand();
4 Commonpeople peopleWhoGetTheNews = new Commonpeople(newsStand);
5 Commonpeople peopleWhoDonotFeed = new Commonpeople(newsStand);
6 Commonpeople people = new Commonpeople();
7 newsStand.setNews("2011-11-11");
8 newsStand.removeObserver(peopleWhoDonotFeed);
9 newsStand.setNews("2012-12-24");
10 }
————————————————————————————————————————————————————运行如下: