观察者模式

观察者模式:当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知它的依赖对象。观察者模式属于行为型模式。简单举个例子:有三个警察同时在监视一个小偷,都在等小偷偷东西从而人赃并获,当小偷开始偷窃时,三个警察同时都有所行动。

本人学习网站->http://www.runoob.com/design-pattern/observer-pattern.html。下面是一个demo的UML图。

下面是一个简单警察小偷的demo:

定义小偷类:

public class Thief {
    private List<Police> police = new ArrayList<>();
    public void steal() {
        System.out.println("I'm stealing things aha");
        police.stream().forEach(p -> p.policeReaction());
    }
    void add(Police p) {
        police.add(p);
    }

}

定义警察抽象类: 

public abstract class Police {
    protected Thief thief;

    protected String name;

    public abstract void policeReaction();
}

定义警察1:

public class Police1 extends Police {

    public Police1(Thief thief, String name) {
        this.thief = thief;
        this.name = name;
        //将该警察添加进观察列表
        thief.add(this);
    }
    @Override
    public void policeReaction() {
        System.out.println(name + "警官抓贼啦");
    }
}

定义警察2:

public class Police2 extends Police {

public Police2(Thief thief, String name) {
this.thief = thief;
this.name = name;
thief.add(this);
}

@Override
public void policeReaction() {
System.out.println(name + "警官抓贼啦");
}
}

测试demo:

public static void main(String[] args) {
        Thief thief = new Thief();
        new Police1(thief,"JACK");
        new Police2(thief,"LUCAS");
        thief.steal();
    }

-------------------------------------------------------------------------------------------

个人感觉,了解了设计模式对看源码有非常大的帮助,很多优秀的框架中运用了大量的设计模式,值得借鉴和思考,大家加油!

 

posted @ 2018-07-04 17:15  rayallenbj  阅读(134)  评论(0编辑  收藏  举报