观察者模式

观察者模式:
需要了解原理:https://www.runoob.com/design-pattern/observer-pattern.html
观察者模式:java实现方式

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

public class ObserverTest {
    public static void main(String[] args) {
        Object number = new Object();
        number.addObserver(new BinaryObserver());
        number.addObserver(new OctalObserver());
        number.addObserver(new HexaObserver());
        number.setData(10);
        number.setData(15);
        number.setData(20);
    }
}

//被观察者
class Object  extends  Observable {
    private int data;

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
        setChanged();
        notifyObservers();
    }
}
//观察者1
class BinaryObserver implements Observer{

    public void update(Observable o, java.lang.Object arg) {
        Object myObserable=(Object) o;
        System.out.println("BinaryObserver: " + Integer.toBinaryString(myObserable.getData()));
    }
}

//观察者2
class OctalObserver implements Observer{

    public void update(Observable o, java.lang.Object arg) {
        Object myObserable=(Object) o;
        System.out.println("OctalObserver: " + Integer.toOctalString(myObserable.getData()));
    }
}

//观察者3
class HexaObserver implements Observer{

    public void update(Observable o, java.lang.Object arg) {
        Object myObserable=(Object) o;
        System.out.println("HexaObserver: " + Integer.toHexString(myObserable.getData()));
    }
}

你可能感兴趣的:(Java,设计模式)