美文网首页我爱编程
Kotlin学习笔记(3)观察者模式代码示例

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

作者: zhaolp2005 | 来源:发表于2018-06-27 14:21 被阅读0次

有时候我们需要监控属性,当属性发生变化时,我们会接收变化并处理
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<String>){
    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)观察者模式代码示例

    本文链接:https://www.haomeiwen.com/subject/xwvbyftx.html