Android Design Pattern source code parsing-Proxy pattern, androidproxy

Source: Internet
Author: User

Android Design Pattern source code parsing-Proxy pattern, androidproxy
Android Design Pattern source code parsing-Proxy pattern

This article analyzes the Proxy mode in the source code parsing of Android Design Patterns
Android: 5.0
ANALYST: singwhatiwanna; analysis status: completed; Proofreader: Mr. Simple; proofreader status: proofread

Proxy mode in Binder

Before talking about the proxy mode in the Binder, we need to first look at the simple implementation of the proxy mode, this part uses the code example and uml class diagram in the article "JAVA and mode" proxy mode.

1. Mode Introduction

The proxy mode is the structure mode of the object. The proxy mode provides a proxy object for an object and controls the reference to the original object by the proxy object.

Application scenarios

A person or institution acts on behalf of another person or institution. In some cases, a client does not want or cannot directly reference an object, and the proxy object can play a mediation role between the client and the target object.

2. UML class diagram

Roles
  • Abstract object role: Declares the common interfaces of the target object and the proxy object, so that the proxy object can be used wherever the target object can be used.

  • Target object role: defines the target object represented by the proxy object.

  • Proxy object role: the proxy object contains references to the target object, so that the target object can be operated at any time. The proxy object provides the same interface as the target object, so that the target object can be replaced at any time. A proxy Object usually performs an operation before or after the client call is passed to the target object, instead of simply passing the call to the target object.

3. Introduction to simple implementation of the Mode

The following uses an abstract method to implement the proxy mode.

Source code

Abstract object role

Public abstract class implements actobject {// operate public abstract void operation ();}

Target object role

Public class RealObject extends actobject {@ Override public void operation () {// some operations System. out. println ("some operations ");}}

Proxy object role

Public class ProxyObject extends actobject {RealObject realObject = new RealObject (); @ Override public void operation () {// you can perform related operations before calling the target object System. out. println ("before"); realObject. operation (); // after calling the target object, you can perform related operations System. out. println ("after ");}}

Client

public class Client {    public static void main(String[] args) {        AbstractObject obj = new ProxyObject();        obj.operation();    }}
4. Use of proxy mode in Binder

Intuitively, the Binder is a class in Android, which inherits the IBinder interface. From the IPC perspective, Binder is a cross-process communication method in Android. It can also be understood as a virtual physical device. Its device driver is/dev/Binder, this communication method is not available in linux. From the Android Framework perspective, the Binder is a bridge between ServiceManager and various managers (ActivityManager, WindowManager, etc) and corresponding ManagerService. From the Android Application layer, the Binder is the medium for communication between the client and the server. When you bindService, the server returns a Binder object that contains service calls from the server, the client can obtain the services or data provided by the server. The services here include common services and AIDL-based services.

A very important role of the Binder is to package the client's request parameters through Parcel and then upload them to the remote server. The remote server parses the data and performs corresponding operations. Meanwhile, the client thread is suspended, after the server method is executed, write the returned result to another Parcel and pass it back to the client through the Binder. After the client receives the Parcel of the returned data, the Binder parses the content in the data packet and returns the original result to the client. Now, the entire Binder process is complete. It can be seen that the Binder is more like a data channel. The Parcel object is transmitted across processes in this channel. It is not responsible for how the two sides communicate, both parties only need to package and package data in accordance with the agreed specifications.

To better describe the Binder, we first manually implement a Binder. To make the logic clearer, we can simplify it here to simulate a banking system. This bank provides only one function: querying the balance and passing an int id, the bank will set your balance to id * 10 to meet everyone's fortune dream.

package com.ryg.design.manualbinder;import android.os.IBinder;import android.os.IInterface;import android.os.RemoteException;public interface IBank extends IInterface {    static final String DESCRIPTOR = "com.ryg.design.manualbinder.IBank";    static final int TRANSACTION_queryMoney = (IBinder.FIRST_CALL_TRANSACTION + 0);    public long queryMoney(int uid) throws RemoteException;}

2. Create a Binder and implement the above interface

package com.ryg.design.manualbinder;import android.os.Binder;import android.os.IBinder;import android.os.Parcel;import android.os.RemoteException;public class BankImpl extends Binder implements IBank {    public BankImpl() {        this.attachInterface(this, DESCRIPTOR);    }    public static IBank asInterface(IBinder obj) {        if ((obj == null)) {            return null;        }        android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);        if (((iin != null) && (iin instanceof IBank))) {            return ((IBank) iin);        }        return new BankImpl.Proxy(obj);    }    @Override    public IBinder asBinder() {        return this;    }    @Override    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)            throws RemoteException {        switch (code) {        case INTERFACE_TRANSACTION: {            reply.writeString(DESCRIPTOR);            return true;        }        case TRANSACTION_queryMoney: {            data.enforceInterface(DESCRIPTOR);            int uid = data.readInt();            long result = this.queryMoney(uid);            reply.writeNoException();            reply.writeLong(result);            return true;        }        }        return super.onTransact(code, data, reply, flags);    }    @Override    public long queryMoney(int uid) throws RemoteException {        return uid * 10l;    }    private static class Proxy implements IBank {        private IBinder mRemote;        Proxy(IBinder remote) {            mRemote = remote;        }        @Override        public IBinder asBinder() {            return mRemote;        }        public java.lang.String getInterfaceDescriptor() {            return DESCRIPTOR;        }        @Override        public long queryMoney(int uid) throws RemoteException {            Parcel data = Parcel.obtain();            Parcel reply = Parcel.obtain();            long result;            try {                data.writeInterfaceToken(DESCRIPTOR);                data.writeInt(uid);                mRemote.transact(TRANSACTION_queryMoney, data, reply, 0);                reply.readException();                result = reply.readLong();            } finally {                reply.recycle();                data.recycle();            }            return result;        }    }}

OK, so far, our Binder is complete. Here we only need to create the server and client, and the two can communicate through our Binder. This is not an example here. Our purpose is to analyze the use of the proxy mode in the Binder.

We can see that there is a class called "Proxy" in the implementation of the above Binder. Its construction method is as follows:

  Proxy(IBinder remote) {      mRemote = remote;  }

The Proxy class receives an IBinder parameter. this parameter is actually the result of re-packaging the Binder object returned by the onBind method in the server Service on the client, because the client cannot directly communicate with the server through the packaged Binder, therefore, the client must use the Proxy class to communicate with the server. Here, the Proxy serves as the Proxy, and all client requests are represented through the Proxy. The specific workflow is as follows: after receiving the request from the client, the Proxy will package the Request Parameters of the client to the Parcel object, and then send the Parcel object to the server through its internal Ibinder object, after the server receives data and executes the method, it returns the result to the Proxy of the client. After the Proxy parses the data, it returns the result to the real caller of the client. Obviously, the above analysis is a typical proxy mode. As for how the Binder transmits data, this involves a very low level of knowledge, which is hard to understand, but the core idea of data transmission is shared memory.

5. Advantages and Disadvantages
  • Added localization scalability and access control for objects
Disadvantages
  • Will generate additional proxy classes
Android technology exchange group
  • 29969245

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.