[Android & amp; Java] design pattern code: Observer Pattern

Source: Internet
Author: User

[Android & Java] design pattern code: Observer Pattern

The observer is like a person who is interested in many things, like music, electronic products, games, and stocks. Changes in these things can attract the attention of fans and always pay attention to them. In the code, we also have such a way to design some interesting ideas. Today, I will write a Demo to describe this idea.

Well, programmers are not good at speaking. Read the code first.

1. demo structure:

2. first, create our theme Subject. He is the star class of our demo and inherits the Observable class. As the name suggests, it is the class to be observed. Other observers are very keen on him (including you)

 

/*** Define a topic 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; policychanged ();} public String getName () {return name;} public void setName (String name) {this. name = name; policychanged ();} public String getMessage () {return message;} public void setMessage (String message) {this. message = message; yychanged ();}/*** after the data changes, we will be notified that the "Observer" Data subscribed to this topic has been updated */private void policychanged () {setChanged (); yyobservers () ;}@ 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); dest. writeString (name); dest. writeString (message);} public static final Parcelable. creator
 
  
CREATOR = new Creator
  
   
() {@ 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 must have an identity. Otherwise, how can he call it an Observer? He wants to implement our Observer interface and his update method: this is the entry to receive the latest news!

 

 

/*** This is Mr. bean, a 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 (Obs ErverBean, subject updated: + this. subjcet. toString (); if (hanlder! = Null) {Message msg = hanlder. obtainMessage (2); msg. obj = subjcet; msg. sendToTarget ();}}}
4. Our main interface is coming. Haha, this Activity is also an observer. How can one observer be? There are at least two. Let's talk nonsense and look at the code.

 

 

/*** One way to use the observer mode. The main function here is to show how topics we are interested in change and notify their subscribers, that is, the Observer * the effect of this example is not the focus, mainly to increase the understanding of the Observer. * @ Author jan * Date: July 22, 2015 20:27:01 */public class ObserverActivity extends Activity implements Observer {private static final String TAG = ObserverActivity; // display the changed topic content private TextView mSubText1; private TextView mSubText2; // The subscribed topic private Subject mSubject; private UpdateRunnable runnable; // The observer entity class. Another subscribed object private ObserverBean bean; private Handler mHandler = new Handler (new Handler. callback () {@ Overridepublic boolean handleMessage (Message msg) {if (msg. what = 1) {// update the Subject received by the ObserverActivity Subject sj1 = (Subject) msg. obj; mSubText1.setText (sj1.getId () ++ sj1.getName () ++ sj1.getMessage (); return true;} else if (msg. what = 2) {// update the topic content received by Mr. bean Subject sj2 = (Subject) msg. obj; mSubText2.setText (sj2.getId () ++ sj2.getName () ++ sj2.getMessage (); return true ;}return false ;}); @ Overr Ideprotected 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 the topic instance mSubject = new Subject (); bean. setSubjcet (mSubject); // The topic object adds the observer to establish an association. Several people may be interested in a topic, as shown in the following code. Two audience mSubject is added. AddObserver (bean); mSubject. addObserver (this); runnable = new UpdateRunnable (); mHandler. postDelayed (runnable, 1000);} // This method is triggered if the topic content changes. Here we will update the latest content of the topic @ 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. sendToTarg Et () ;}@ Overrideprotected void onDestroy () {super. onDestroy (); mHandler. removeCallbacks (runnable); mSubject. deleteObserver (this); mSubject. deleteObserver (bean);}/*** regularly changes the topic content every second * @ author jan */class UpdateRunnable implements Runnable {int I = 0; @ Overridepublic void run () {if (mSubject! = Null) {I ++; mSubject. setId (I); mSubject. setName (I + activity log); mSubject. setMessage (hitting the Tiger tonight -- + I);} mHandler. postDelayed (this, 1000 );}}}

5. Last

 

Conclusion: The Observer mode defines the one-to-many relationship between a series of objects. When an object changes its status, other dependent persons will receive a notification.

 

 

 

Related Article

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.