java学习

java学习

 

设计模式之观察者模式

观察者模式(有时又被称为发布(publish )-订阅(Subscribe)模式、模型-视图(View)模式、源-收听者(Listener)模式或从属者模式)是软件设计模式的一种。在此种模式中,一个目标物件管理所有相依于它的观察者物件,并且在它本身的状态改变时主动发出通知。这通常透过呼叫各观察者所提供的方法来实现。此种模式通常被用来实现事件处理系统。
public interface Observer {
public void update(int low,int heigh,String weather);
void removeSubject();
}
public interface Subject {
public void registerObserver(Observer observer);
public void removeObserver(Observer observer);
public void notifyObserver();
}
public class Android implements Observer{
public Android(){}
private Subject subject;
public Android(Subject subject) {
this.subject = subject;
this.subject.registerObserver(this);
}
@Override
public void update(int low, int heigh, String weather) {
System.out.println("Android" + low + "," + heigh + "," + weather);
}
public void removeSubject() {
subject.removeObserver(this);
}
}
public class IPad implements Observer{
private Subject subject;
public IPad(){}
public IPad(Subject subject) {
this.subject = subject;
subject.registerObserver(this);
}
@Override
public void update(int low, int heigh, String weather) {
System.out.println("IPad " + low + "," + heigh + "," + weather);
}
public void removeSubject() {
subject.removeObserver(this);
}
}
public class WeatherData implements Subject{
private int low;
private int heigh;
private String weather;
private List<Observer> observerList = new ArrayList<Observer>();
public void setData(int low,int heigh,String weather) {
this.low = low;
this.heigh = heigh;
this.weather = weather;
notifyObserver();
}
public int getLow() {
return low;
}
public int getHeigh() {
return heigh;
}
public String getWeather() {
return weather;
}
@Override
public void registerObserver(Observer observer) {
if(!observerList.contains(observer)) {
observerList.add(observer);
}
}
@Override
public void removeObserver(Observer observer) {
if(observerList.contains(observer)) {
observerList.remove(observer);
}
}
@Override
public void notifyObserver() {
for(Observer o : observerList) {
o.update(getLow(), getHeigh(), getWeather());
}
}
}
public class Test {
public static void main(String[] args) {
WeatherData wd = new WeatherData();
Android android = new Android(wd);
//android.removeSubject();
IPad ipad = new IPad(wd);
//ipad.removeSubject();
wd.setData(2, 23, "---");
}
}

posted on 2017-09-08 10:09 杨军威 阅读(132) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜