Introduction to design pattern Observer Pattern and Its Application in Android

Source: Internet
Author: User

Recently, I have been studying the design model. A good way to learn more is to write down my experiences. Record your understanding. Now I read the book head. frist design pattern. Good. Anyone who wants to learn the design model can read this book.


Observer <observer> mode (sometimes referred to as publish-subscribe <publish/subscribe> mode, Model-View <model/View> mode, source-listener <source/listener> mode or dependent <dependents> mode) is a software design model. In this mode, a target object manages all observer objects that depend on it and actively sends notifications when its status changes. This is usually done by calling the methods provided by various observers. This mode is usually used to implement an event processing system. (From Baidu encyclopedia)

(Revised in December May 31)

See the following structure:

Start with a small example

Observer interface:

public interface ISubscribe {void getNewPaper();}

Observer implementing the observer interface:

Individual subscriber:

Public class personalsubscriber implements isubscribe {private string strname; Public void setnewspapername (string strname) {This. strname = strname;} Public String getnewspapername () {return strname ;}@ overridepublic void getnewpaper () {// todo auto-generated method stubsystem. out. println ("I am a personal user and I got my newspaper:" + getnewspapername ());}}

Enterprise subscribers:

Public class extends isesubscriber implements isubscribe {private string strname; Public void setnewspapername (string strname) {This. strname = strname;} Public String getnewspapername () {return strname ;}@ overridepublic void getnewpaper () {// todo auto-generated method stubsystem. out. println ("I am an enterprise user and I got my newspaper:" + getnewspapername ());}}

Observer: Subject

public abstract class Publish { public List<ISubscribe> list;public Publish(){list = new ArrayList();}    public void registered(ISubscribe iSubscribe){    list.add(iSubscribe);    }        public void unregistered(ISubscribe iSubscribe){    list.remove(iSubscribe);    }        public abstract void sendNewsPaper();}

The abstract class is used here.

The following is an implementation:

public class PostOffice extends Publish{@Overridepublic void sendNewsPaper() {// TODO Auto-generated method stubIterator iterator = list.iterator();while(iterator.hasNext()){((ISubscribe) iterator.next()).getNewPaper();}}}

Test:

Public static void main (string [] ARGs) {// todo auto-generated method stubpostoffice postoffice = new postoffice (); // obtain the personal user personalsubscriber person = new personalsubscriber (); person. setnewspapername ("Southern Weekend"); // get the enterprise user enterprisesubscriber enterprise = new enterprisesubscriber (); enterprise. setnewspapername (""); // register the observer postoffice. registered (person); postoffice. registered (enterprise); // issue a newspaper postoffice. sendnewspaper ();}

Test results:

I am an individual user and I got my newspaper: Southern Weekend, I am an enterprise user. I got my newspaper: Enterprise newspaper

Below are some errors in the May 18 version: there is an error parsing later!

For example, John subscribed to Southern Weekend from the post office, Li Si subscribed to Beijing News from the post office, and Wang Wu subscribed to Southern Metropolis Daily from the post office. When a newspaper arrives at the post office, the Post Office delivers the newspaper to the subscriber. The subscriber does not need to go to the post office every day to ask whether the newspaper has arrived at the post office.

The following code starts: it should first be a subscriber interface:

Package CN. demo; public interface isubscribe {// subscribe to a newspaper from the Post Office Public void registered (postoffice); // unsubscribe a newspaper public void unregistered (postoffice) from the post office ); // obtain the newspaper name public void getnewspaper ();}

The third method is not required. The first two methods must be available. (The first two are not required, and the third method must exist)

There are three subscriber classes:

John:

Package CN. demo; public class zhangsan implements isubscribe {private string mname; private string mnewspapername; Public zhangsan (string mname, string mnewspapername) {This. mname = mname; this. mnewspapername = mnewspapername;} Public String getname () {return mname;} Public String getnewspapername () {return mnewspapername;} @ overridepublic void registered (postoffice) {postoffice. registerednewspaper (this) ;}@ overridepublic void unregistered (postoffice) {postoffice. unregisterednewspaper (this) ;}@ overridepublic void getnewspaper () {// todo auto-generated method stubsystem. out. println ("I am" + getname () + ", I received my subscription" + getnewspapername ());}}

Li Si:

Package CN. demo; public class Lisi implements isubscribe {private string mname; private string mnewspapername; Public Lisi (string mname, string mnewspapername) {This. mname = mname; this. mnewspapername = mnewspapername;} Public String getname () {return mname;} Public String getnewspapername () {return mnewspapername;} @ overridepublic void unregistered (postoffice) {postoffice. unregisterednewspaper (this);} @ overridepublic void registered (postoffice) {postoffice. registerednewspaper (this) ;}@ overridepublic void getnewspaper () {// todo auto-generated method stubsystem. out. println ("I am" + getname () + ", I received my subscription" + getnewspapername ());}}

Wang Wu:

Package CN. demo; public class wangwu implements isubscribe {private string mname; private string mnewspapername; Public wangwu (string mname, string mnewspapername) {This. mname = mname; this. mnewspapername = mnewspapername;} Public String getname () {return mname;} Public String getnewspapername () {return mnewspapername;} @ overridepublic void registered (postoffice) {postoffice. registerednewspaper (this) ;}@ overridepublic void unregistered (postoffice) {postoffice. unregisterednewspaper (this) ;}@ overridepublic void getnewspaper () {// todo auto-generated method stubsystem. out. println ("I am" + getname () + ", I received my subscription" + getnewspapername ());}}

Each of the three subscribers can subscribe to a newspaper or cancel the subscription. In fact, information about subscribers is stored in the post office class.

Post office class: (the post office class should inherit an abstract class or interface (subject), which is not implemented here)

import java.util.ArrayList;import java.util.List;public class PostOffice {private List<ISubscribe> SubscribeList = new ArrayList<ISubscribe>();public void registeredNewsPaper(ISubscribe subscribe) {SubscribeList.add(subscribe);}public void unregisteredNewsPaper(ISubscribe subscribe) {if (subscribe != null) {SubscribeList.remove(subscribe);}}public void getNewsPaper(boolean bool) {if (bool) {sendNewsPaper();}}public void sendNewsPaper() {for(ISubscribe subscribe : SubscribeList) {subscribe.getNewsPaper();}}}

In this class, the sendnewspaper () method is used to traverse all subscribers.
Test class:

Public static void main (string [] ARGs) {// todo auto-generated method stubpostoffice mpostoffice = new postoffice (); isubscribe zhangsan = new zhangsan ("zhangsan ", "Southern Weekend"); isubscribe Lisi = new Lisi ("Li Si", "Beijing News"); isubscribe wangwu = new wangwu ("Wang Wu ", "Southern Metropolis Daily"); // subscribe to the newspaper zhangsan. registered (mpostoffice); Lisi. registered (mpostoffice); wangwu. registered (mpostoffice); // The Post Office receives the newspaper and starts issuing the mpostoffice. getnewspaper (true); // Li Si unsubscribes to Lisi. unregistered (mpostoffice); // The Post Office receives the newspaper and starts issuing the mpostoffice. getnewspaper (true );}

Print result:

I'm Michael Zhang, and I received my subscription for "Southern Weekend". I am Li Si. I received my subscription for "Beijing News". I am Wang Wu, I received the Southern Metropolis Daily subscribed to by me, I am Zhang San, and I received the subscribed Southern Weekend, I am Wang Wu, and I received the subscribed Southern Metropolis Daily

Here is just a simple example, and the code you will find is redundant. The three subscriber classes are almost the same, because they are not added with their own attributes in the class, it can be replaced by a person class. The three classes are written here to make the display clear.

For the example in April May 18, the observer does not need to register or cancel the registration. The implementation of their methods is also called by the observer registration and cancellation of registration, it is better to directly use the method of the observer.

In Android, the button. setonclicklistener () method is a common observer mode: of course, as we all know, onclick is a famous callback method, so we will not study callback here, so don't worry too much.

Check the Code:

Button button1 = (Button)findViewById(R.id.button1);        Button button2 = (Button)findViewById(R.id.button2);        Button button3 = (Button)findViewById(R.id.button3);        button1.setOnClickListener(this);        button2.setOnClickListener(this);        button3.setOnClickListener(this);    }@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch(v.getId()) {case R.id.button1 ://do some thingcase R.id.button2 ://do some thingcase R.id.button3 ://do some thing}}

Click button. setonclicklistener () to register the listener. It is equivalent to Lisi. Registered (mpostoffice) in the post office. The error here should be postoffice. Registered (person) in the first example ). The onclick RESPONSE event is equivalent

public void sendNewsPaper() {for(ISubscribe subscribe : SubscribeList) {subscribe.getNewsPaper();}}

Subscribe. getnewspaper () in this example. View. onclicklistener is equivalent to the post office. View, that is, the button is our subscriber, which is equivalent to Michael Jacob. We can also add some switch judgments in getnewspaper.

Finally, what if our post office wants to implement callback like button?

Isubscribe; @ overridepublic void getnewspaper () {// todo auto-generated method stubsystem. out. println ("I am" + getname () + ", I received my subscription" + getnewspapername (); isubscribe. getnewspaper ();}

Here, we get a bit of code. In fact, we can create another interface. Do not know whether you can understand, do not understand welcome to leave a message to discuss. Thank you. It's time to complete the weekend!


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.