1. 对象间的一种一对多的依赖关系,当一个对象状态发生改变时,所有依赖于它的对象都将得到通知并自动更新
2.观察者模式的结构
另一种实现方案
package com.javapatterns.observer.variation;
public class Client
{
private static ConcreteSubject subject;
private static Observer observer;
public static void main(String[] args)
{
subject = new ConcreteSubject();
observer = new ConcreteObserver();
subject.attach(observer);
subject.change("new state");
}
}
package com.javapatterns.observer.variation;
public class ConcreteObserver implements Observer
{
public void update()
{
System.out.println("I am notified");
}
}
package com.javapatterns.observer.variation;
public class ConcreteSubject extends Subject
{
private String state;
public void change(String newState)
{
state = newState;
this.notifyObservers();
}
}
package com.javapatterns.observer.variation;
public interface Observer
{
void update();
}
package com.javapatterns.observer.variation;
import java.util.Vector;
import java.util.Enumeration;
abstract public class Subject
{
/**
* @associates <{Observer}>
* @link aggregation
* @supplierCardinality 0..*
*/
private Vector observersVector = new java.util.Vector();
public void attach(Observer observer)
{
observersVector.addElement(observer);
System.out.println("Attached an observer.");
}
public void detach(Observer observer)
{
observersVector.removeElement(observer);
}
public void notifyObservers()
{
java.util.Enumeration enumeration = observers();
while (enumeration.hasMoreElements())
{
System.out.println("Before notifying");
((Observer)enumeration.nextElement()).update();
}
}
public Enumeration observers()
{
return ((java.util.Vector) observersVector.clone()).elements();
}
}
其它例子可参考http://blog.csdn.net/csh624366188/article/details/7477116
观察者模式与MVC模式关系
MVC是观察者模式、合并模式、策略模式设计模式组合
观察者模再举一例:
我和妹妹跟妈妈说:“妈妈,我和妹妹在院子玩,饭好了,告诉我们一下,请问这是什么模式
1.这是观察者模式