Reprint Please specify source: http://blog.csdn.net/lhy_ycu/article/details/39755577
Observer (Observer) pattern definition: Defines a one-to-many dependency between objects, so that when an object changes state, the object that relies on it is notified and automatically follows the new. Java has already provided the default implementation of the Observer observer pattern, and Java's support for the observer pattern is mainly embodied in the observable class and the Observer interface. Look at the UML Model Diagram first:
first, UML model diagram
Second, the code implementation
/** Example: We go to the market to buy food * Small traders--theme */class food extends Observable {/** dish name */private String name;/** vegetable price */private float PRICE;PU Blic Food (String name, float price) {this.name = Name;this.price = Price;} Public String GetName () {return name;} public float GetPrice () {return price;} public void Setprice (float price) {this.price = price;/** * Setting the status of the menu has been changed */this.setchanged ();/** * notify "all" customers who are watching (already registered) After callback observer Update method is updated * * Here can reflect the object of one-to-many: once a small trader updates the price (that is, an object changes the state), it will automatically notify all customers (dependent on the object will be notified) * and automatically update * * This.notifyobservers (price);}} /** * Customer--viewer */class customer implements Observer {private String name;public customer (String name) {this.name = name;} Public String GetName () {return name;} @Overridepublic void Update (Observable o, Object Arg) {if (o instanceof && arg instanceof Float) {Food food = (food) o;float price = (float) arg; System.out.println ("Hello:" + this.name + "," + food.getname () + "The price has changed, now the price is:" + prices + "Yuan/catty");}} /** * Client Test class * * @author Leo */public class Test {public static void Main (string[] args) {Food food = new Food ("potato", 1.0f); Customer Zhangsan = new Customer ("Zhang San"); Customer Lisi = new Customer ("John Doe"),/** * Add Customer */food.addobserver (Zhangsan); Food.addobserver (Lisi);/** * update Price */ Food.setprice (1.5f);}}
third, the application scenario
GUI frame, meteorological observation, etc.
Iv. SummaryBe sure to call the Setchanged () method before notifying all observers to set the state of the observer to be changed so that notifyobservers () will not be updated with the Observer Update method.
If there are different opinions or omissions in the above content, please give us some valuable suggestions or comments.
Finally, you can try to use the following UML model for specific code implementation, with the source
Java Design Patterns Rookie series (ii) modeling and implementation of observer patterns