这个模式挺简单的,就是一个类调用另一个类。。
先来张uml草图。。。
import java.util.ArrayList;
import java.util.List;
interface Observerable{
public void addObserver(Observer o);
public void delObserver(Observer o);
public void notifyAlls();
}
interface Observer{
public void addMessage(String message);
}
class WeChatServer implements Observerable{
private List<Observer> list;
private String message;
public WeChatServer() {
this.list=new ArrayList<Observer>();
}
@Override
public void addObserver(Observer o) {
// TODO Auto-generated method stub
list.add(o);
}
@Override
public void delObserver(Observer o) {
// TODO Auto-generated method stub
list.remove(o);
}
@Override
public void notifyAlls() {
// TODO Auto-generated method stub
for(int i=0;i<list.size();i++) {
Observer o=list.get(i);
o.addMessage(message);
}
}
public void addInformation(String message) {
this.message=message;
System.out.println("微信更发送了新的推送信息:"+message);
notifyAlls();
}
}
class User implements Observer{
private String name;
private String message;
public User(String name){
this.name=name;
}
@Override
public void addMessage(String message) {
// TODO Auto-generated method stub
this.message=message;
read();
}
private void read() {
System.out.println(name+"接收到了信息:"+message);
}
}
public class GCZDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
WeChatServer wc=new WeChatServer();
Observer u1=new User("张三");
Observer u2=new User("李四");
Observer u3=new User("王五");
wc.addObserver(u1);
wc.addObserver(u2);
wc.addObserver(u3);
wc.addInformation("PHP是世界上最好的语言");
System.out.println("----------------------");
wc.delObserver(u1);
wc.addInformation("Java是世界上最好的语言");
wc.delObserver(u2);
wc.delObserver(u3);
System.out.println("----------------------");
wc.addInformation("别走啊卧槽!");
}
}