Observer Mode Analysis

Source: Internet
Author: User

I. Observer mode Overview

The observer mode (also known as the Model-View Mode, the source-listener mode, or the dependent mode) is a software design mode. 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 the event processing system.

The observer mode consists of the following four parts:

1) Abstract target role (subject): The target role knows its observer. Multiple observers can observe the same target. It also provides interfaces for registering and deleting observer objects. The target role is often implemented by abstract classes or interfaces.

2) Abstract observer role (observer): defines an update interface for objects that need to be notified when the target changes. Abstract observer roles are mainly implemented by abstract classes or interfaces.

3) a specific target role (concrete subject): stores the relevant status into each concrete observer object. When its status changes, a notification is sent to its various observers.

4) A specific observer role (concrete observer): stores the relevant status, which should be consistent with the target status. The observer update interface is implemented to make its status consistent with that of the target. This role can also maintain a reference pointing to the concrete subject object.

 

The observer mode conforms to the interface isolation principle and achieves loose coupling between objects. The UML diagram is as follows:

 

Ii. Why the observer mode?

The observer mode is frequently used in actual projects. It is most commonly used in Gui systems and subscription-publishing systems. Because one important role of this model is decoupling, so that the dependencies between them are smaller, or even less dependent. In the GUI system, the UI of an application is variable. Especially in the early stage, the application interface changes frequently with changes in business or product requirements, but the business logic remains unchanged, the GUI system needs a mechanism to deal with this situation, so that the UI Layer is decoupled from the specific business logic, and the observer mode will be used in this case. The observer mode is also called the publish/subscribe mode. The observer mode defines a one-to-many dependency, allowing multiple observer objects to listen to a topic object at the same time. When the status of this topic object changes, it notifies all observer objects so that they can automatically update themselves.

Application Example:

Introduction
  • This is a library used to intercept real-time SMS messages for Android. It can be used for text message filtering to obtain the desired content. It can be used for app projects that need to automatically enter the SMS verification code.
Function
  • Used to listen to the currently received SMS messages
  • Filter received text messages to get the desired content

First, define the observer class smsobserver, including a series of methods applied to the observer:

Public class smsobserver extends contentobserver {private context mcontext; public static final int msg_received_code = 1001; private smshandler mhandler; /*** defines three different observer Construction Methods */Public smsobserver (activity context, smsresponsecallback callback, smsfilter) {This (New smshandler (callback, smsfilter); this. mcontext = context;} public smsobserver (activity context, smsresponsecallback callba CK) {This (New smshandler (callback); this. mcontext = context;} public smsobserver (smshandler handler) {super (handler); this. mhandler = handler;}/*** set the SMS filter * @ Param smsfilter */Public void setsmsfilter (smsfilter) {mhandler. setsmsfilter (smsfilter);}/***** Method for registering the observer for SMS change */Public void registersmsobserver () {URI uri = Uri. parse ("content: // SMS"); If (mcontext! = NULL) {mcontext. getcontentresolver (). registercontentobserver (Uri, true, this) ;}/ ***** Method for canceling the observer for SMS change */Public void unregistersmsobserver () {If (mcontext! = NULL) {mcontext. getcontentresolver (). unregistercontentobserver (this);} If (mhandler! = NULL) {mhandler = NULL ;}/ ***** Method for sending the status to the observer when the SMS is changed */@ override public void onchange (Boolean selfchange, Uri URI) {super. onchange (selfchange, Uri); If (URI. tostring (). equals ("content: // SMS/raw") {return;} uri inboxuri = Uri. parse ("content: // SMS/inbox"); // inbox try {cursor c = mcontext. getcontentresolver (). query (inboxuri, null, "date DESC"); If (C! = NULL) {If (C. movetofirst () {string address = C. getstring (C. getcolumnindex ("Address"); string body = C. getstring (C. getcolumnindex ("body"); If (mhandler! = NULL) {mhandler. obtainmessage (msg_received_code, new string [] {address, body }). sendtotarget ();} log. I (getclass (). getname (), "Sender:" + address + "" + "SMS content:" + body);} C. close () ;}} catch (securityexception e) {log. E (getclass (). getname (), "failed to get sms permission", e);} catch (exception e) {e. printstacktrace ();}}}

Initialize the observer instance:

Smsobserver = new smsobserver (this, new smsresponsecallback () {@ override public void oncallbacksmscontent (string smscontent) {// receive SMS here}, new verificationcodesmsfilter ("180 "));

Register SMS change listener

  • After registering the listener, the SMS observer has started the SMS change listener. Next, you only need to receive the SMS and process the SMS.
public void registerSMSObserver() {        Uri uri = Uri.parse("content://sms");        if (mContext != null) {            mContext.getContentResolver().registerContentObserver(uri,                    true, this);        }    }   smsObserver.registerSMSObserver();

Unregister the SMS change listener

  • When you do not need to use the text message reception function, please cancel the text message listener. Otherwise, you can still receive the text message later.
/***** Unregister the SMS change Observer */Public void unregistersmsobserver () {If (mcontext! = NULL) {mcontext. getcontentresolver (). unregistercontentobserver (this);} If (mhandler! = NULL) {mhandler = NULL ;}} smsobserver. unregistersmsobserver ();

 

 

Observer Mode Analysis

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.