设计模式-观察者模式

目的:

定义一种一对多的对象依赖关系这样当一个对象改变状态时,所有依赖它的对象都将自动通知或更新。

程序示例:

在遥远的土地上生活着霍比特人和兽人的种族。他们都是户外生活的人所以他们密切关注天气的变化。可以说他们不断地关注着天气。

1.定义天气类型合观察者接口

public enum WeatherType{
    SUNNY("Sunny"),
    RAINY("Rainy"),
    WINDY("Windy"),
    COLD("Cold");

    private final String description;

    WeatherType(String description) {
        this.description = description;
    }

    public String getDescription() {
        return description;
    }

    @Override
    public String toString() {
        return this.name().toLowerCase();
    }
}

public interface WeatherObserver{
    void  update(WeatherType currentWeather);
}

2.实现各种的观察者

@Slf4j
public class Orcs implements WeatherObserver{
    @Override
    public void update(WeatherType currentWeather) {
        log.info("The orcs are facing " + currentWeather.getDescription() + " weather now");
    }
}

@Slf4j
public class Hobbits implements WeatherObserver{
    @Override
    public void update(WeatherType currentWeather) {
        log.info("The hobbits are facing " + currentWeather.getDescription() + " weather now");
    }
}

3.观察对象

public class Weather{
    private WeatherType currentWeather;
    private final List<WeatherObserver> observers;

    public Weather() {
        currentWeather=WeatherType.SUNNY;
        this.observers = new ArrayList<>();
    }


    //添加观察者

    public void addObserver(WeatherObserver obs){
        observers.add(obs);
    }

    //移除观察者

    public void removeObserver(WeatherObserver obs){
        observers.remove(obs);
    }

    //让时间随着天气流逝
    public void timePasses(){
        WeatherType[] weatherTypes = WeatherType.values();
        //获取当前枚举的序号+1%长度 实现天气轮转
        currentWeather=weatherTypes[(currentWeather.ordinal()+1)%weatherTypes.length];
        notifyObservers();
    }

    //通知观察员
    public void notifyObservers(){
        observers.forEach(x->x.update(currentWeather));
    }

}

4.测试输出

 

        Weather weather = new Weather();
        weather.addObserver(new Orcs());
        Hobbits hobbits = new Hobbits();
        weather.addObserver(hobbits);

        weather.timePasses();
        /*
        The orcs are facing Rainy weather now
        The hobbits are facing Rainy weather now
         */

        weather.timePasses();
        /*
        The orcs are facing Windy weather now
        The hobbits are facing Windy weather now
         */

        weather.removeObserver(hobbits);

        weather.timePasses();
        /*
        The orcs are facing Cold weather now
         */

        weather.timePasses();
        /*
        The orcs are facing Sunny weather now
         */

类图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值