Design Pattern-Observer Pattern

Source: Internet
Author: User
Observer mode: You can check whether a variable has changed. The observer mode is used for class observable and interface observer. Directly run the code: Set a person class that inherits observable and serves as the observer. Public class person extends observable {private string name; Public String getname () {return name;} public void setname (string name) {This. name = Name; setchanged (); yyobservers () ;}note: Observe the name of person. If the name changes, immediately notify the user. setchanged () notifyobservers () the two methods are used to implement the notification function. To set an observer, You need to implement the observer interface: I will implement a textview
Public class mytestview extends textview implements observer {public mytestview (context, attributeset attrs, int defstyle) {super (context, attrs, defstyle);} public mytestview (context, attributeset attrs) {super (context, attrs);} public mytestview (context) {super (context);} Private Static int number = 0; @ override public void Update (observable, object Data) {settext ("data changed" + number); Number ++ ;}}


As you can see, I want to change the display content in textview as long as the name of person has changed.

Take a look at the main class: Public class mainactivity extends actionbaractivity {private person test; @ override protected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); mytestview text = (mytestview) findviewbyid (R. id. text); test = new person (); test. addobserver (text); // Add the observer to the observer. Button change = (button) findviewbyid (R. id. change); change. setonclickli Stener (New onclicklistener () {@ override public void onclick (view v) {test. setname ("hahah"); // click an event to change the name value of the person object. }});}}
This is the simplest implementation of the observer mode.



From Weizhi note (wiz)

Design Pattern-Observer Pattern

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.