Kotlin学习笔记(3)观察者模式代码示例

有时候我们需要监控属性,当属性发生变化时,我们会接收变化并处理
Java实现方式

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

public class Observation {

    public static void main(String[] args){
        ExchangeRateObservable observable = new ExchangeRateObservable();
        observable.addObserver(new ExchangeRateObserver());

        String exchangeRate = "6.4";
        observable.setObject(exchangeRate);
        exchangeRate = "6.5";
        observable.setObject(exchangeRate);
    }

    //被观察者,监控可变化的变量
    static class ExchangeRateObservable extends Observable{
        private String object = null;

        public String getObject() {
            return object;
        }

        public void setObject(String object) {
            this.object = object;
            setChanged();
            notifyObservers();
        }
    }

    //观察者
    static class ExchangeRateObserver implements Observer{

        @Override
        public void update(Observable o, Object arg) {
            ExchangeRateObservable observable = (ExchangeRateObservable)o;
            System.out.println("exchangeRate: "+ observable.getObject());
        }
    }
}

exchangeRate: 6.4
exchangeRate: 6.5

kotlin提供了很好的支持,实现更简单

fun main(args: Array){
    println("output:")

    var exchangeRate: String by Delegates.observable(""){
        property, oldValue, newValue ->
        println("$oldValue -> $newValue")
    }
    exchangeRate = "6.4"
    exchangeRate = "6.5"
}

output:
 -> 6.4
6.4 -> 6.5

你可能感兴趣的:(Kotlin学习笔记(3)观察者模式代码示例)