Luckylau's Blog

设计模式之观察者模式

​ 观察者(Observer)模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象,主体对象的状态变化会通知所有观察者对象。观察者模式又叫做发布-订阅(Publish/Subscribe)模式、模型-视图(Model/View)模式、源-监听器(Source/Listener)模式或从属者(Dependents)模式。

​ 以微信订阅号的关注和消息推送为例,无论是微信的订阅号、微博的大V、喜马拉雅的音频专辑,都可以被关注或取消关注,当有新的文章、消息、音频作品出现的时候,订阅了的粉丝都会收到消息。所以我们可以抽象出来一个共同的抽象类Publisher来实现这些公共的方法:

发布者

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
public abstract class Publisher {
private List<Subscriber> funs = new ArrayList<Subscriber>();
private String message;
public void publishMessage(String message) {
this.message = message;
notifyAllSubscribers();
}
public String getMessage() {
return message;
}
public void addSubscriber(Subscriber subscriber) {
funs.add(subscriber);
}
public void delSubscriber(Subscriber subscriber) {
funs.remove(subscriber);
}
public void notifyAllSubscribers() {
Iterator<Subscriber> it = funs.iterator();
while (it.hasNext()) {
it.next().update(this);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
public class WeixinPublisher extends Publisher {
private String dingyuehao;
public WeixinPublisher(String dingyuehao) {
this.dingyuehao = dingyuehao;
}
@Override
public String toString() {
return "微信订阅号[" + dingyuehao + "]";
}
}

订阅者

1
2
3
public interface Subscriber {
void update(Publisher publisher);
}
1
2
3
4
5
6
7
8
9
10
11
public class WeixinAccount implements Subscriber {
private String accountName;
public WeixinAccount(String accountName) {
this.accountName = accountName;
}
public void update(Publisher publisher) {
System.out.println(accountName + "的微信收到了来自" + publisher + "的推送文章: " + publisher.getMessage());
}
}

Client.java

1
2
3
4
5
6
7
8
9
10
public class Client {
public static void main(String[] args) {
WeixinPublisher publisher = new WeixinPublisher("luckytech");
publisher.addSubscriber(new WeixinAccount("张三"));
publisher.addSubscriber(new WeixinAccount("李四"));
publisher.addSubscriber(new WeixinAccount("王五"));
publisher.publishMessage("Java24种设计模式-观察者模式");
}
}
Luckylau wechat
如果对您有价值,看官可以打赏的!