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