Common Java class libraries-Observer design mode (Observable class Observer Interface)

Source: Internet
Author: User


To implement the Observer mode, you must rely on the Observable class and Observer interface provided in the java. util package.

Import java. util. *; class House extends Observable {// indicates that the House can be viewed as private float price; // price public House (float price) {this. price = price;} public float getPrice () {return this. price;} public void setPrice (float price) {// The observer's attention should be paid to each modification. setChanged (); // set the change point super. yyobservers (price); // The price is changed this. price = price;} public String toString () {return "House price:" + this. price ;}}; class HousePriceObserver implements Observer {private String name; public HousePriceObserver (String name) {// set the name of each buyer this. name = name;} public void update (Observable o, Object arg) {if (arg instanceof Float) {System. out. print (this. name + "observed price changed to:"); System. out. println (Float) arg ). floatValue () ;}}; public class ObserDemo01 {public static void main (String args []) {House h = new House (1000000 ); export hpo1 = new HousePriceObserver ("buyer A"); HousePriceObserver hpo2 = new HousePriceObserver ("buyer B"); HousePriceObserver hpo3 = new HousePriceObserver ("buyer C"); h. addObserver (hpo1); h. addObserver (hpo2); h. addObserver (hpo3); System. out. println (h); // output house price h. setPrice (666666); // modify the house price System. out. println (h); // output house price }};

 

Result: The house price is: 1000000.0 buyers C observed the price changed to: 666666.0 buyers B observed the price changed to: 666666.0 buyers A observed the price changed to: 666666.0 house price: 666666.0

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.