Observer mode, the author used to check the order once, but do not know that there is this mode, when using the Observer omitted n more if else
In the author's view, the observer model is compared to try to change the state of an object, many objects should also be based on this state to do the corresponding action, of course, the Observer mode is only to open a door, more hope is flexible use, rather than rigidly in detail,
We can learn from the implementation of the same interface class to put into the collection, and then facilitate the collection of public methods to do the corresponding work, first look at the class diagram
Liar design mode-Class diagram
Based on the class diagram, I wrote the following simple example.
/** * notifier Abstract interface */ public interface INotify { public void Notifysub (); public void AddSub (isubject subject); public void Removesub (isubject subject);
/***/Publicinterface isubject {publicvoid updatestate (String state);}
/*** Specific notifying person*/ Public classNotifyImplementsINotify {Privatelist<isubject> subjects =NewArraylist<>(); @Override Public voidAddSub (isubject subject) {Subjects.add (subject); } @Override Public voidremovesub (isubject subject) {subjects.remove (subject); } @Override Public voidnotifysub () { for(Isubject subject:subjects) {subject.updatestate ("Place an Order"); } }}
/***/Publicclassimplements isubject { @Override publicvoid updatestate (String state) { System.out.println (state); }}
/***/Publicclass Test {publicstatic void Main (string[] args) { new Notify (); Notify.addsub (new Subject ()); Notify.notifysub (); }}
Operation Result:
Place an order.
Design patterns that optimize our code, decouple, easily expand, and maintain, but if you don't understand the essence of design patterns, mechanically may not be able to get the best results.
I believe that the idea of absorbing design patterns is the key to learning. The above is the author's understanding of the observer, hope to help the learning of small partners!
Java Watcher mode (big talk design mode)