Copyright notice: This article is Codeagles original article, can be reproduced at will, but must indicate the source in a clear place!!
What is the observer mode? The Observer Pattern is a “publisher-subscriber” Pattern. Also known as model-view mode, source-listener mode, and so on. How it works: A target object manages all dependent observer objects, and actively notifies its observers when the target itself changes.
Key words: observed target itself, active notification.
To use observer mode, there are a few things to know:
- Why use it
- What are the advantages
- What are the disadvantages
- How to use
Called introduction to design patterns, because design pattern is a kind of thought, a kind of code structure, it comes from a lot of people’s experience, are relatively flexible, only central idea is the same, the author only for example, that’s easy to understand, as far as possible, of course, ability is limited, still need to the reader to understand more, on their own projects, or in practical experience.
- Why? Of course, because one object changes state and then notifies the other objects, what happens after that is up to the designer. In fact, there are many application cases, such as key add Listener. Of course, AWT, Swing is relatively unfamiliar.
For an example of life, flight reservations, when does the plane take off, all the passengers were looking at the tickets, so all the passengers is the observer, they need to observe the dynamic of plane, the plane is the target object, the day when the plane takes off, airline will send all the passengers aboard the aircraft a message: “The plane will take off tomorrow at what time, blah, blah…” “All observers will receive a text message (an unsolicited notification from the target) and the passengers will know what the plane is doing.
- What are the advantages? Maybe it’s too easy to understand, the observer and the observed are abstractly coupled, coupled but low coupled, and secondly it can listen for triggering events, and the whole point of observing is to know when I’m going to act.
- What are the disadvantages? It’s pretty obvious.
- All observers of an object need to be notified, and the time cost is high.
- In this mode, observers only know that the target object has changed, but they do not know how.
- There are other shortcomings, do not understand, skill is too shallow, do not write temporarily.
- How does it work? ####Talk is cheap, show me the code. ####Subject class
package ObserverPattern; import java.util.ArrayList; import java.util.List; Public class Subject {// observers private List<Observer> observers = new ArrayList<Observer>(); Private int state; private int state; //setter and getter public intgetState() {
return state;
}
public void setState(int state) { this.state = state; // set the state and actively notifyAllObservers notifyAllObservers(); } // Add observers to the Observer list public void addObservers(Observer ob){observers.add(ob); } // Notify all observers of public voidnotifyAllObservers() {
for(Observer ob:observers){// Observers respond ob.make_response(); }}}Copy the code
# # # # Obeserver abstract classes
package ObserverPattern; Public abstract class Observer {// Fovetail the Observer's entity class, so that subclasses can bind directly to the protected Subject Subject; public abstract void make_response(); }Copy the code
####FirstObserver observer entity class
package ObserverPattern; Public class FirstObserver extends Observer{public FirstObserver(Subject sub){this.subject=sub; / / to start listening to this. Subject. AddObservers (this); } @Override public voidmake_response() {
System.out.println("Observer 001, my role is to output the object's changed state:"+subject.getState()); }}Copy the code
#### Observer entity class for SecondObserver
package ObserverPattern; Public class SecondObserver extends Observer {public class SecondObserver(Subject sub) {this. Subject = sub; / / to start listening to this. Subject. AddObservers (this); } @Override public voidmake_response() {
System.out.println("Observer 002, my role is to convert the target object's status code to binary:"+Integer.toBinaryString(subject.getState())); }}Copy the code
# # # # ObserverPattern Demo
package ObserverPattern;
public class ObserverPattern {
public static void main(String[] args) {
Subject subject = new Subject();
FirstObserver fo= new FirstObserver(subject);
SecondObserver so =new SecondObserver(subject);
System.out.println("First setting status code: 520");
subject.setState(520);
System.out.println("Second change status code :1314"); subject.setState(1314); }}Copy the code
#### Output result:
The first time I set the status code: 520 observer 001, I output the changed state of the object: 520 Observer 002, I output the changed state of the object: 1314 Observer 002, my role is to convert the status code of the target object to binary: 10100100010Copy the code
### End of summary here, this article is about ideas and simple principles, if you have any questions, please leave a comment below. There are already classes in JAVA that support the observer pattern. When using this mode, it is important to note that if the program executes sequentially with an observer error, the program will die, which is not hard to imagine. Examples, may not be appropriate, there are good examples are also welcome to post in the message area, talk about together.