An introduction to the application and advantages of the observer model for Android source learning _android

Source: Internet
Author: User
Tags abstract event listener inheritance
Observer Pattern Definition
Define a one-to-many dependency between objects so then one object changes state, all its dependents AER notified and Updated automatically.
Defines a one-to-many dependency between objects so that when an object changes state, all objects that depend on it are notified and automatically updated.

as shown in the figure above (intercepted from the head Patterns), it consists of four main parts
1. Subject the observed person. is an interface or abstract class that defines the duties that the observer must fulfill, and it must be able to dynamically add, cancel, and manage the observer and inform the Observer.
2. Observer Observer. When the Observer receives the message, the update operation is performed and the received information is processed.
3. ConcreteSubject the specific observed person. Define the business logic of the Observer, and define which events to notify.
4. Concreteobserver specific observers. Each observer has a different way of handling information after receiving it, and each observer has its own processing logic.
What are the advantages of the Observer model?
An abstract coupling between the observer and the observed is very easy to expand, whether it is to increase the observer or the observer.
According to the principle of single responsibility, the responsibility of each class is unitary, then how to put each single responsibility into a real complex logical relationship, the Observer model can play a role in the bridge.
The observer pattern is typical of loose coupling.
In the Android code, one of the classic uses of the observer model is the event listener model of the Android control.
The following is a brief description of the design principles and characteristics of the Android interactive event transmission
An interaction event is a related event that is triggered when a user interacts with an application through a keystroke, touch, or slide operation. The Android control tree shows that interactive events are propagated down the control tree from top to bottom. The Android Control tree summary diagram looks like this:

When the parent control at the top of the control tree receives an interaction event, the target control object for the event is determined first, and if the event is exactly what it needs, the event is intercepted, or an attempt is made to distribute the event down to the corresponding child control and propagate the event downward to the push, until the event is processed or ignored.

Android defines a series of event functions named view.on*** in the view class to receive and process all kinds of interactive events, such as the user's keystrokes, which can be received by the View.onkeydown function. Each child control that derives from the view class can handle the events required by the control by overloading the event functions.

For example, if a control needs to handle the action that the user presses the return key, it can be implemented by overloading the View.onkeydown function:
Copy Code code as follows:

/*
* @see android.app.activity#onkeydown (int, android.view.KeyEvent)
*/
@Override
public boolean onKeyDown (int keycode, keyevent event) {
Listening and processing return operations
if (keycode = = Keyevent.keycode_back) {
DoSomething ();
return true;
}
return false;
}

The return value of event function is an important means to control event propagation. If the event function returns True, the control has received and completed processing of the event without further delivery of the event, or if the event function returns FALSE, the control object failed to handle the event (or, although it has been done, it still needs further processing), You need to continue passing to find the control object that can handle it.

For container control ViewGroup, one of its responsibilities is to propagate interactive events into its child controls. For different events, ViewGroup can choose different ways of propagation. For example, if it is a touch event, the ViewGroup object needs to determine which child control the area on which the event occurred is located on, thereby assigning the event to the child control for processing. However, event handling through inheritance is not flexible enough to cause a large number of child control types to appear in the system, and the reusability of each control is poor. Therefore, "combination" is used instead of "inheritance". Based on this idea, the view class provides a set of event listener functions for developers to handle the corresponding events, and this has the event listener model that uses the observer pattern to complete the Android control. The developer can construct an external observer object and a control object's event listener interface binding to get the event message.
or the above key event as an example, through the listener to handle the implementation of the following is shown
Copy Code code as follows:

Final View.onkeylistener listener = new Onkeylistener () {
@Override
public boolean OnKey (View v, int keycode, keyevent event) {
Handling Return key events
if (keycode = = Keyevent.keycode_back) {
DoSomething ();
return true;
}
return false;
}
};
。。。
Muisetbutton = (Button) Findviewbyid (R.id.setvalue);
Bind a button to a listening object
Muisetbutton.setonkeylistener (listener);

By using external objects to handle interactive events, the coupling is low, so that each class control has a better degree of reusability, and no new controls are constructed to handle the event.
second, now start to see how the source code is organized using the "Observer mode"
1. See the Onkeylistener interface in the view class source code:
Copy Code code as follows:

/**
* Interface definition for a callback to being invoked when a key event is
* Dispatched to this view. The callback would be invoked before the key
* Event is given to the view.
*/
Public interface Onkeylistener {
/**
* Called when a key is dispatched to a view. This allows listeners to
* Get a chance to respond before the target view.
*
* @param v The View the key has been dispatched to.
* @param keycode The code for the physical key, that is pressed
* @param event The KeyEvent object containing full information about
* The event.
* @return True If the listener has consumed the event, false otherwise.
*/
Boolean OnKey (View v, int keycode, keyevent event);
}

2. Again the view class defines the private member Monkeylistener (by combination):
Private Onkeylistener Monkeylistener;
3. Register Listener
Copy Code code as follows:

/**
* Register a callback to being invoked when a key is pressed into this view.
* @param l The key listener to attach to this view
*/
public void Setonkeylistener (Onkeylistener l) {
Monkeylistener = l;
}

4. The rest is left to the developer to construct the external observer object to bind to the key's event interface to get the event message.
Finally, let us remember the design principle underpinning the "observer pattern": strive for loosely coupled designs between objects.

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.