1 Observer pattern: There are observers, then there must be a corresponding observer, the essence of the observer pattern can be summed up-when the observed changes, can timely inform the observation value, the observer can be notified after the corresponding treatment.
2 Sample Code
2.1 Defines the Observer interface, the method is that when the observer receives the notice of the Observer, the corresponding processing will be made
Obverser {change ();}
2.2 Definition of two observers
Observer1 Obverser {change () {System. println (); }}
Observer2 Obverser {change () {System. println (); }}
2.3 Define the observer (since to be notified, there should be a way to save the object to be notified and to add a delete notification object, which can be extended; method of notification)
Subject {notification (); Add (Obverser obverser); Del (Obverser Obverser); Opreation ();}
2.4 The implementation class of the observer (why it is defined here as an abstract class, because it is possible that different observers will notify different observers)
Msubject Subject {vector<obverser> =vector<obverser> (); Notification () {enumeration<obverser> enumeration=. elements (); (Enumeration.hasmoreelements ()) {enumeration.nextelement (). change (); }} Add (Obverser obverser) {. Add (Obverser); } del (Obverser obverser) {. Remove (Obverser); }}
2.5 Specific one of the observed
Msubsubject Msubject {opreation () {System.. println (); Notification (); }}
2.6 Testing
Main {main (string[] args) {Subject subject=msubsubject (); Subject.add (Observer1 ()); Subject.add (Observer2 ()); Subject.opreation (); }}
2.7 Test Results
5555555555555555
11111111111111
222222222222222222
Design Pattern-Observer mode (OBSERVER)