[android& Java] Talking about design pattern-code: Observer mode Observer

Source: Internet
Author: User

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 this kind of way to design some interesting ideas. Write a demo today to describe this idea, using Java's built-in observer to implement this idea.

Well, the program ape is not verbal, look at the code first.

Structure of the 1.demo:

2. First create our Theme class subject, he is our demo of the Star class. Inherit the observable, as the name implies, is the observed class. Other observers are looking at him, but it's a good thing (actually contains 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 us 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 needs 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. One Subscriber object  */public class Observerbean implements Observer {private Handler hanlder;private Subject subjcet;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 say little nonsense and look at the code.

/** * A way to use the observer pattern, where the basic function is to show how topics of interest we are interested in changing and informing their subscribers, the observer * This sample is not the focus, mainly to add to observer understanding. * @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, we also have a 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 = new Observerbean (mhandler);//Generate an instance of the topic Msubject = new subject ( ); Bean.setsubjcet (msubject);//The Subject object joins the Observer and establishes the association. A topic may be of interest to several people, such as the following. Added 2 spectators msubject.addobserver (bean); Msubject.addobserver (this); runnable = new updaterunnable (); mhandler.postdelayed (runnable, 1000);} Let's say the subject content changes. The method is triggered. We are here to update the latest content of the display topic @overridepublic void Update (Observable Observable, Object data) {Subject SJ = null;if (Observable instanc EOF 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.


Download the demo link

Suggested Related blogs: 1. Design pattern of the seven---observer pattern (Observer)

2.Android Observer Viewer Mode

-------------------------------------------------------------------------------------Update Line--------------------------------- --------------------------------------------------------------------

Date: July 24, 2015

About the Observer pattern in our code, the reality is often more complex. There may be multiple combinations, because observable is an abstract class in Java. is a class rather than an interface. This makes it more difficult for us to use it flexibly, because Java classes can only inherit a class and cannot inherit as much as an interface. That means we'd better be able to implement a similar interface to replace him. The first thing I did in the recommended blog was to do it.



[android&amp; Java] Talking about design pattern-code: Observer mode Observer

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.