观察者接口:
/**
* Created by cuboo on 2016/10/14.
*/
public interface Observer {
public <T> void update(Observable o,T agr);
}
观察者具体实现类:
/**
* Created by cuboo on 2016/10/14.
*/
public class concreteObserver implements Observer {
private String[] Message;
private String obsName;
//重写update获得被观察者的数据
@Override
public <T> void update(Observable o, T agr) {
this.Message = (String[]) agr;
this.obsName = o.getObsName();
}
public void print(){
System.out.println(obsName+":");
for (String s :
Message) {
System.out.print(s +" ");
}
System.out.println();
}
}
被观察者抽象类:
import java.util.ArrayList;
/**
* Created by cuboo on 2016/10/14.
*/
public abstract class Observable {
private boolean change = false;
private String obsName;
private ArrayList<Observer> Observers = new ArrayList<>();
//添加观察者
public synchronized void addObserver(Observer o){
if (o == null)
throw new NullPointerException();
if (!Observers.contains(o)){
Observers.add(o);
}
}
//删除观察者
public synchronized void deleteObserver(Observer o){
if (o == null)
throw new NullPointerException();
if (Observers.contains(o)){
Observers.remove(o);
}
}
//通知观察者
public <T> void notifyObserver(T agrs){
synchronized (this){
if (change){
clearChange();
for (Observer o:Observers) {
o.update(this,agrs);
}
}
}
}
//统计注册的观察者数量
public synchronized int countObservers(){
return Observers.size();
}
//被观察者是否改变
public synchronized boolean isChanged(){
return change;
}
protected synchronized void setChange(){
change = true;
}
private synchronized void clearChange(){
change = false;
}
public void setObsName(String obsName) {
this.obsName = obsName;
}
public String getObsName() {
return obsName;
}
}
/**
* Created by cuboo on 2016/10/14.
*/
public class concreteObservable extends Observable {
private String[] Message;
public void setMessage(String[] message) {
Message = message;
}
public String[] getMessage() {
return Message;
}
public void notifyObserver() {
this.setChange();
this.notifyObserver(getMessage());
}
}
示例:
/**
* Created by cuboo on 2016/10/14.
*/
public class observertest {
public static void main(String agrs[]){
concreteObservable cob = new concreteObservable();
concreteObserver observer = new concreteObserver();
concreteObserver observer1 = new concreteObserver();
cob.setObsName("this is ObservableA test");
cob.setMessage(new String[]{"1","2","3","4"});
cob.addObserver(observer);
cob.addObserver(observer1);
cob.notifyObserver();
System.out.println(cob.countObservers());
observer.print();
observer1.print();
}
}