import java.util.ArrayList;
import java.util.List;
public abstract class Subject {
/**
* 保存女朋友的集合
*/
private List<Observer> list = new ArrayList();
/**
* 添加人
*
* @param server
*/
public void attach(Observer server) {
list.add(server);
System.out.println("我新交了一个女朋友,名字叫做:" + server.getName());
}
/**
* 移除人
*
* @param server
*/
public void detach(Observer server) {
list.remove(server);
System.out.println("我和她分手了");
}
/**
* 通知所有的女朋友更新状态
*/
public void notifyObserver(String state) {
for (Observer observer : list) {
observer.update(state);
}
}
}
public interface Observer {
public String getName();
void update(String state);
}
public class MessageSubject extends Subject {
public void onClick(String state) {
notifyObserver(state);
}
}
public class GFObserver implements Observer {
public GFObserver(String name) {
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void update(String state) {
System.out.println(this.name + "接收到新消息,男朋友最新状态:" + state);
}
}
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
Observer obser1 = new GFObserver("范冰冰");
Observer obser2 = new GFObserver("杨幂");
Observer obser3 = new GFObserver("Sisi");
Observer obser4 = new GFObserver("sasa");
MessageSubject message = new MessageSubject();
message.attach(obser1);
message.attach(obser2);
message.attach(obser3);
message.attach(obser4);
message.onClick("我在大保健");
message.detach(obser1);
message.onClick("泡吧");
}
}