From http://blog.csdn.net/shuangde800
Understanding observer ModeLet's take a look at how newspapers and magazines subscribe to. 1. newspapers are published. 2. If you subscribe to a newspaper from a newspaper, you can send it to you as long as they have published a new newspaper. As long as you are their subscribers, you will always receive newspapers. 3. When you do not want to read newspapers, you can cancel the subscription and they will not send new newspapers. 4. As long as the newspaper is still running, someone will always subscribe to the newspaper or cancel the newspaper.
Publisher + subscriber = observer Mode
If you know what the newspaper subscription is, you actually know what the observer mode is, but the name is not the same: the publisher calls it a "topic ), the subscriber is changed to "observer" (observer)
Define observer Mode
The observer mode defines one-to-multiple dependencies between objects. In this way, when an object changes its state, all dependent objects will receive and automatically update the object.
Observer pattern class diagram:
Design principles
Efforts to design loose coupling between interaction objects
The loosely coupled design allows us to build an elastic OO system to cope with changes because the mutual dependency between objects is minimized.
Design principles involved in the Observer Mode
Principle 1: Identify the change aspect in the program and then separate it from the fixed aspect
In the observer mode, the state of the topic and the number and type of the observer are changed. In this mode, you can change objects dependent on the topic state, but you do not need to change the topic. This is called Advance planning!
Principle 2: For interface programming, not for implementation programming
Both the topic and observer use interfaces: The Observer uses the topic interface to register with the topic, and the topic uses the observer interface to notify the observer. In this way, the two can operate normally and have the advantage of loose coupling.
Principle 3: Multi-Purpose Combination and less inheritance
The observer mode uses the "Combination" method to combine many observers into the topic. This relationship between objects is generated not by inheritance, but by using combinations at runtime.