观察者模式

博客围绕观察者模式展开,虽未给出具体内容,但观察者模式是程序设计领域重要概念。它定义了对象间一对多依赖关系,当一个对象状态改变,依赖它的对象会收到通知并自动更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package observer;

import java.util.Observable;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 观察者模式
 * */
public class WeatherDate extends Observable {
    private String tempature;
    private String humidity;
    private String pressure;
    private Boolean change;
    //构造方法
    public WeatherDate(){}
    /**
     * 通知观察者
     * */
    public void measurementsChanged(){
        setChange();
        if(change){
            notifyObservers();
        }
        change=false;
    }
    /**
     * 更新状态
     * */
    public void setMeasurementsChanged(String tempature, String humidity, String pressure){
        this.tempature=tempature;
        this.humidity=humidity;
        this.pressure=pressure;
    }
    /**
     * change的作用,例如......
     * 做一个控制,不是一更新就通知观察者,所以有点重要,有set,就有get和clear
     * */
    public void setChange(){
        change=true;
    }
    public void clearChange(){
        change=false;
    }

    public String getTempature() {
        return tempature;
    }

    public void setTempature(String tempature) {
        this.tempature = tempature;
    }

    public String getHumidity() {
        return humidity;
    }

    public void setHumidity(String humidity) {
        this.humidity = humidity;
    }

    public String getPressure() {
        return pressure;
    }

    public void setPressure(String pressure) {
        this.pressure = pressure;
    }

    public Boolean getChange() {
        return change;
    }

    public void setChange(Boolean change) {
        this.change = change;
    }
}

 

package observer;

import java.util.Observable;
import java.util.Observer;

public class Condition implements Observer {
    private Observable observable;
    private String tempature;
    private String hunidity;

    /**
     * 构造方法
     * 将该对象加入观察者
     * */
    public Condition(Observable observable){
        this.observable=observable;
        observable.addObserver(this);
    }
    /**
     * Emmm.....
     * 先判断是否是WeatherDate类型,获取WeatherDate更新的值
     * */

    @Override
    public void update(Observable o, Object arg) {
        if(o instanceof WeatherDate){
            WeatherDate weatherDate=(WeatherDate)o;
            this.tempature=weatherDate.getTempature();
            this.hunidity=weatherDate.getHumidity();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值