设计模式-观察者模式

介绍

观察者模式定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。

使用场景
1.一个抽象模型有两个方面,其中一个方面依赖于另一个方面。将这些方面封装在独立的对象中使它们可以各自独立地改变和复用。
2.一个对象的改变将导致其他一个或多个对象也发生改变,而不知道具体有多少对象将发生改变,可以降低对象之间的耦合度。
3.一个对象必须通知其他对象,而并不知道这些对象是谁。
4.需要在系统中创建一个触发链,A对象的行为将影响B对象,B对象的行为将影响C对象……,可以使用观察者模式创建一种链式触发机制。

优点
1.观察者和被观察者之间是抽象耦合的。
2.增强系统灵活性、可扩展性。

缺点
1.程序中包括一个被观察者、多个观察者、开发和调试等内容会比较复杂。
2.消息通知默认是顺序执行,执行效率较低。

UML类图

Observer.jpg

代码实现

Sun.java

public class Sun {

    private List animals;
    private int state;
    private final int SUNRISE = 0;
    private final int SUNSET = 1;
    
    public int getState() {
        return state;
    }
    public void setState(int state) {
        this.state = state;
    }
    
    public void attach(Animal animal) {
        animals.add(animal);
    }
    
    public void notifyObservers() {
        for(Animal animal : animals) {
            animal.update();
        }
    }
}

Animal.java

public abstract class Animal {

    protected Sun sun;
    protected final int SUNRISE = 0;
    protected final int SUNSET = 1;
    public abstract void update();
}

Monkey.java

public class Monkey extends Animal {

    public Monkey(Sun sun) {
        this.sun = sun;
        this.sun.attach(this);
    }
    
    @Override
    public void update() {
        System.out.println(sun.getState());
    }
}

Owl.java

public class Owl extends Animal {

    public Owl(Sun sun) {
        this.sun = sun;
        this.sun.attach(this);
    }
    
    @Override
    public void update() {
        System.out.println(sun.getState());
    }
}

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