观察者模式

Intent

  • Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
  • Encapsulate the core (or common or engine) components in a Subject abstraction, and the variable (or optional or user interface) components in an Observer hierarchy.
  • The "View" part of Model-View-Controller.

Structure

观察者模式_第1张图片

实例Demo

  1. 问题描述: 动物园,饲养员通知动物消息;
  2. 结构图:


    观察者模式_第2张图片
    Observer by keith
  3. 实现代码:
public class Observer {
    public static void main(String[] args){
        Feeder feeder=new Feeder();
        Observable ob1=new Cat();
        Observable ob2=new Dog();
        Observable ob3=new Sheep();

        //register the observable
        feeder.register(ob1);
        feeder.register(ob2);
        feeder.register(ob3);

        //change the msg
        feeder.changeMsg("time to eat");
    }
}
//observable interface
interface Observable {
    // method to be called by subject
    void update(String msg);
}
//Cat
class Cat implements Observable {

    @Override
    public void update(String msg) {
        System.out.println(getClass().getSimpleName() + " received: " + msg);
    }
}
//Dog
class Dog implements Observable {

    @Override
    public void update(String msg) {
        System.out.println(getClass().getSimpleName() + " received: " + msg);
    }
}
//Sheep
class Sheep implements Observable {

    @Override
    public void update(String msg) {
        System.out.println(getClass().getSimpleName() + " received: " + msg);
    }
}
//subject interface
interface Subject {
    void register(Observable obs);

    void unregister(Observable obs);

    void notifyDataChanged(String msg);
}
class Feeder implements Subject {

    private List observables;

    private String message;

    public Feeder() {
        this.observables = new ArrayList<>();
    }

    public void changeMsg(String msg) {
        message = msg;
        notifyDataChanged(msg);
    }

    @Override
    public void register(Observable obs) {
        observables.add(obs);
    }

    @Override
    public void unregister(Observable obs) {
        observables.remove(obs);
    }

    @Override
    public void notifyDataChanged(String msg) {
        for (Observable obs : observables) {
            obs.update(msg);
        }
    }
}
  1. 运行结果:
Cat received: time to eat
Dog received: time to eat
Sheep received: time to eat

Refenrence

  1. Design Patterns
  2. 设计模式

你可能感兴趣的:(观察者模式)