The observer, like a person, is interested in a lot of things, like music, electronics, Game, stock and so on, these things change can arouse the attention of enthusiasts and always pay attention to them. In the code, we also have a way to design some interesting ideas. Write a demo today to describe this idea.
Well, programmers are bad words, look at the code first.
Structure of the 1.demo:
2. First create our Theme class subject, he is our demo Star class, inherited the observable, as the name implies, is the class of observation, the other observers are looking for him oh (in fact, including you OH)
/** * defines a subject class * @author Jan */public class Subject extends Observable implements parcelable {private int id;private String Name;private String message;public Subject () {}public Subject (Parcel Parcel) {this.id = Parcel.readint (); this.name = Parcel.readstring (); this.message = Parcel.readstring ();} public int getId () {return ID;} public void setId (int id) {this.id = Id;notifychanged ();} Public String GetName () {return name;} public void SetName (String name) {this.name = Name;notifychanged ();} Public String GetMessage () {return message;} public void Setmessage (String message) {this.message = Message;notifychanged ();} /** * After the data has changed, notify our subscribers that the subject's "Watcher" data has been updated */private void notifychanged () {setchanged (); Notifyobservers ();} @Overridepublic String toString () {return "Subject [id=" + ID + ", name=" + name + ", message=" + message+ "]";} @Overridepublic int describecontents () {return 0;} @Overridepublic void Writetoparcel (Parcel dest, int flags) {dest.writeint (this.id);d est.writestring (name); Dest.writestring (MessaGE);} public static final parcelable.creator<subject> Creator = new creator<subject> () {@Overridepublic subject[] NewArray (int size) {return new subject[size];} @Overridepublic Subject Createfromparcel (Parcel source) {return new Subject (source);}};3. Well, let's talk about our observer, Mr. Bean, first of all, he has to have an identity, otherwise it's called the Observer, he's going to implement our observer interface, and his update method: This is the portal to receive the latest news!
/** * This is Mr. Bean, a Subscriber object */public class Observerbean implements Observer {private Handler hanlder;private Subject SUBJC Et;public Observerbean (Handler Handler) {this.hanlder = Handler;} Public Subject Getsubjcet () {return subjcet;} public void Setsubjcet (Subject subjcet) {this.subjcet = Subjcet;} @Overridepublic void Update (Observable Observable, Object data) {This.subjcet = (Subject) Observable; LOG.I ("Observerbean", "Subject has been updated:" +this.subjcet.tostring ()); if (hanlder!=null) {Message msg = hanlder.obtainmessage (2); Msg.obj = Subjcet;msg.sendtotarget ();}}}
4. Our main interface comes, haha this activity is also an observer oh, how can an observer be enough, at least 2, to talk less, to look at the code.
/** * A way of using the observer pattern, where the main function is to show how topics of interest we are interested in changing and informing their subscribers that the observer * This example does not focus on the effect, mainly to increase the understanding of observer. * @author Jan * date:2015 July 22 20:27:01 */public class Observeractivity extends Activity implements Observer {private STA Tic final String TAG = "observeractivity";//display changed subject content private TextView msubtext1;private TextView msubtext2;//subscribed topics Priv Ate Subject Msubject;private updaterunnable runnable;//Observer entity class, our other subscription object private Observerbean bean;private Handler Mhandler = new Handler (new Handler.callback () {@Overridepublic Boolean handlemessage (Message msg) {if (msg.what = = 1) {// Updated Observeractivity received topic Subject sj1 = (Subject) msg.obj;msubtext1.settext (Sj1.getid () + "\ n" + sj1.getname () + "\ n" + sj1. GetMessage ()); return true;} else if (msg.what = = 2) {//Update the topic content that Mr. Bean received Subject sj2 = (Subject) msg.obj;msubtext2.settext (Sj2.getid () + "\ n" + sj2.get Name () + "\ n" + sj2.getmessage ()); return true;} return false;}}); @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); sEtcontentview (r.layout.main); mSubText1 = (TextView) Findviewbyid (r.id.subject_id_1); mSubText2 = (TextView) Findviewbyid (r.id.subject_id_2);//Create another subscriber, Mr. Bean Bean = new Observerbean (mhandler);//Generate an instance of the topic Msubject = new subject () ; Bean.setsubjcet (msubject);//The Subject object joins the Observer, creating an association, a subject that may be of interest to several people, such as the addition of 2 spectators msubject.addobserver (beans); Msubject.addobserver (this); runnable = new updaterunnable (); mhandler.postdelayed (runnable, 1000);} If the subject content changes and the method is triggered, we update the latest content of the display topic here @overridepublic void Update (Observable Observable, Object data) {Subject SJ = null; if (observable instanceof Subject) {SJ = (Subject) observable; LOG.D (TAG, "subject-->" +sj.tostring ()); Message msg = mhandler.obtainmessage (1); msg.obj = Sj;msg.sendtotarget ();}} @Overrideprotected void OnDestroy () {Super.ondestroy (); Mhandler.removecallbacks (runnable); msubject.deleteobserver (this); Msubject.deleteobserver (bean);} /** * Periodically change the content of the theme every second * @author Jan */class updaterunnable implements Runnable {int i = 0; @Overridepublic void Run () {if (MS Ubject ! = null) {I++;msubject.setid (i); Msubject.setname (i + "activity log"); Msubject.setmessage ("Play Tiger tonight-" + i);} Mhandler.postdelayed (this, 1000);}}}
5. The final
Summary: The Observer pattern is defined as a one-to-many relationship between a series of objects. When an object changes state, all other dependents are notified.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Android&java] Design Pattern Code article: Observer mode