设计模式:观察者模式
什么是观察者模式
观察者模式是软件设计模式的一种。在此种模式中,一个目标对象管理所有相依于它的观察者对象,并且在它本身的状态改变时主动发出通知。这通常透过呼叫各观察者所提供的方法来实现。此种模式通常被用来实时事件处理系统。
观察者模式的结构
-
Observer(观察者)
-
Subject(被观察对象)
-
ConcreteObserverA和ConcreteObserverB(具体观察者)
-
ConcreteSubjectA和ConcreteSubjectB(具体被观察对象)
一个观察者模式实例
一个聊天群(Group)和多个用户(Member)的关系。要求群里的某个成员说话时,其他的群成员都能看到。
实例代码
Observer
public abstract class Observer {
private String name;
public Observer(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract void send(String message,Subject subject);
public abstract void update(String message,String name);
}
Member
public class Member extends Observer {
public Member(String name){
super(name);
}
@Override
public void send(String message,Subject subject) {
subject.notifyAllObserver(message,this.getName());
}
@Override
public void update(String message,String name) {
System.out.println(this.getName() + " [" + name + "] says : " + message);
}
}
Subject
import java.util.HashSet;
import java.util.Set;
public abstract class Subject {
private String name;
public Subject(String name){
this.name = name;
}
protected Set<Observer> observers = new HashSet<Observer>();
public void join(Observer observer){
System.out.println(observer.getName() + " join " + this.name);
observers.add(observer);
}
public void quit(Observer observer){
System.out.println(observer.getName() + " quit " + this.name);
observers.remove(observer);
}
public abstract void notifyAllObserver(String message,String name);
}
Group
public class Group extends Subject {
public Group(String name) {
super(name);
}
@Override
public void notifyAllObserver(String message,String name) {
for (Observer observer:observers){
if (!name.equals(observer.getName())){
observer.update(message,name);
}
}
}
}
Client
public class Client {
public static void main(String[] args){
Group group = new Group("QQ");
Member member1 = new Member("Jack");
Member member2 = new Member("Monkey");
Member member3 = new Member("Rose");
group.join(member1);
group.join(member2);
group.join(member3);
member1.send("Hello World!",group);
}
}
实例结果
Jack join QQ
Monkey join QQ
Rose join QQ
Rose [Jack] says : Hello World!
Monkey [Jack] says : Hello World!
(完)