Design Patterns observer mode -Java built observer and summary


Observer next

In the previous article, we do weather station project learned how to use the observer pattern dirty dirty bombs by small companies Division Division. In this, we summarize the key points and the observer mode, there is a Java built-in observer mode.

This article Source: Kaige Java (kagejava)

A: the Java built-in viewer

We will use the Java built-in weather station observer will re-write the program once.

Built-in difference viewer:

Subject Object:

1 : Subject name changed into the Observable up; the same function, or registered, removed, observers notice three functions;

2 : Observable object instead of the interface, so when in use, can not be achieved in use, and requires the use of inheritance. Advantage is: because it is the inheritance relationship, so observers in the registration, removed observer, observers notice the specific implementation of these three methods we can not write.

Observer objects:

observer name of the object does not change, function or Update , there is no change. But also the interface objects. 

So why observer not use interfaces and classes it? Because we know that our observer is a different project, not necessarily demand. So, you can only use the interface to define. The specific implementation, each project according to their own projects to achieve the function.

不同:update时候,可以选择将信息主动推送给观察者还是让观察者自己来拉去。在Java内置的观察者模式中,推/拉都可以。

使用Java内置观察者实现的代码:

项目结构:

image1.png

测试类:JavaObserverWeatherMainTest

需要说明的:

public class CurrentConditionJava implements Observer {}

实现的Observer对象所在位置:import java.util.Observer;

public class WeaterDataJava extends Observable {}

继承的Observerable对象所在位置:import java.util.Observable;

运行结果:

image2.png

达到我们预期的效果。说明,使用Java内置的观察者模式成功!

使用Java内置的观察者需要唯一注意的地方:observerable的继承者在datachange时候,需要先setChanged()。如下图:

image3.png

这一点一定要注意。

二:观察者模式总结及关键点

百科上对观察者模式基本介绍:

image4.png

实现方式:

image5.png

观察者模式使用场景:

image6.png


观察者模式四个角色:

image7.png

抽象主题角色(subject)、主题角色具体实现类

抽象观察者角色(observer)、观察者具体实现类

观察者模式的优缺点:

image8.png

观察者模式执行过程

image9.png

从观察者模式中体会,松耦合、高内聚、隔离影响的意义:

松耦合:类与类之间不要太依赖,没有顺序。依赖类不用关系被依赖类的内部是怎么实现的。

对应天气站项目:实现了subject接口的天气对象不需要关系具体的公告板内部怎么实现的,需要做哪些。subject子类之关心公告板是否实现了observer接口类即可。

联系凯哥:

公众号:凯哥Java(kaigejava)

凯哥个人博客:www.kaigejava.com

留个言,加个好友,一起学习

就算实现了observer的公告板对象项目死掉了,subject对象依然可以正常运行。反之,就算subject项目死掉了,依然不会影响observer项目的运行。无非就是公告板不能公布最新数据而已。这就很好的体现了松耦合的好处。

高内聚:对象内部是高内聚的。这样便于调试、扩展等。



Guess you like

Origin blog.51cto.com/kaigejava/2432183