Proxy mode in Android Design Mode

Source: Internet
Author: User

Proxy mode in Android Design Mode
I. Overview

The proxy mode is also one of the commonly used design modes. The proxy mode provides a new object, allowing you to operate on real objects or become a substitute for real objects. it is also common in daily life. for example, A wants to rent A house. In order to save the trouble, A will go to an intermediary. The intermediary will select the house as A substitute. A will enjoy the result of the intermediary screening and pay the rent to the intermediary, this is a typical proxy application in daily life. when you open a webpage at ordinary times, the first page is usually text, and some large resources such as images will be loaded with delay. The proxy mode is also used here.

Composition of proxy mode:

Abstract Subject: Abstract topic-interface for declaring a real topic and a proxy topic

Real Subject: Real topic-Real object, which must be referenced by the proxy topic

Proxy Subject: Proxy topic-Because ProxySubject references RealSubject and implements the same interface as RealSubject, ProxySubject can operate RealSubject and provide some additional operations, such as before & after

 

 

Common scenario-based classification of proxy modes:

1. Virtual Proxy: in fact, the Virtual Proxy uses the Proxy mode to perform a delayed loading on the objects that consume a large amount of resources, that is, when the object will be used to create it.

2. Remote Proxy: Remote Proxy is a classic application, similar to the C/S mode (mainly blocking and controlling Remote method calls and implementing Proxy firewalls ).

3. Smart Reference Proxy: The Intelligent Reference Proxy can provide some additional operations for the referenced object, for example, implementing the actions of the intermediary Searching and Prepare contract.

4. Access Proxy; protection Proxy can control the Access to an object and provide a series of permission management when necessary.

5. copy-on-write Proxy: The Copy (clone) Proxy is actually the branch of the Virtual Proxy, the copy (clone) operation (delayed copy) is performed only when the object changes ).

 

Advantages and disadvantages of proxy mode:

Advantages:

1. The proxy acts as the middle layer between calling and real objects, reducing the coupling between modules and systems

2. You can use a small object to proxy a large object to optimize the system and increase the running speed.

3. Provides RealSubject permission management.

4. It is easy to expand. RealSubject and ProxySubject are all interface-based. After RealSubject changes the business, as long as the interface remains unchanged, ProxySubject can be modified without any modification.

Disadvantages:

1. Same advantage 1. Because the caller and the real object have an intermediate layer, the call response time is increased.

II. Implementation

Here we will use A to look for intermediary rental housing as A Demo to build the proxy mode.

1. Common proxy

Define an abstract topic according to the scenario. IHouse provides three methods: Getting House information, signing for contract, and paying rent.

 

/** * Created by jesse on 15-7-24. */public interface IHouse {    void getHouseInfo();    void signContract();    void payFees();}
Next, define the real theme and implement the IHouse interface. add the house name and price attributes, fill in the excuse method, and log out the house name and price when obtaining the house information; log out the contract signing time when signing the contract, log the price when you pay the rent.

 

public class House implements IHouse{    private final String TAG = House.class.getSimpleName();    private String name;    private double price;    public House(String name, double price){        this.name = name;        this.price = price;    }    @Override    public void getHouseInfo() {        Log.i(TAG, House Info- name: + name +   ¥: + price);    }    @Override    public void signContract() {        Log.i(TAG, Contract: + name +   signed at +               new SimpleDateFormat(HH:mm:ss).format(SystemClock.uptimeMillis()));    }    @Override    public void payFees() {        Log.i(TAG, Bill: name- + name +   $- + price);    }}
To define a House proxy, you also need to implement the IHouse interface and hold the House reference. it can be seen that the agent class is actually like a encapsulated House and provides some additional operations. For example, when the customer wants to view the House, the agent will first retrieve the information of the House in stock, prepare the contract and so on before signing the contract.

 

public class ProxyHouse implements IHouse{    private final String TAG = ProxyHouse.class.getSimpleName();    private IHouse house;    public ProxyHouse(IHouse house){        this.house = house;    }    @Override    public void getHouseInfo() {        Log.i(TAG, searching);        house.getHouseInfo();        Log.i(TAG, search finished);    }    @Override    public void signContract() {        Log.i(TAG, prepare contract);        house.signContract();    }    @Override    public void payFees() {        house.payFees();    }}
For customers, there is no need to directly interact with the House. Here, we first define a House called Don ton estate, with a rent of 5 k, create a House agency, and entrust Don ton estate to the Agency. the customer wants to find a house, sign the contract, and pay the rent directly to the agent.

 

 

        IHouse house = new House(Downton Abbey, 5000);        IHouse proxyHouse = new ProxyHouse(house);        Log.i(TAG, looking for a perfect house);        proxyHouse.getHouseInfo();        Log.i(TAG, thinking);        proxyHouse.signContract();        proxyHouse.payFees();        Log.i(TAG, so easy);

The entire proxy mode flow can be shown in the following sequence diagram. The Client only interacts with the proxy.

2. Virtual proxy

As described earlier, the virtual proxy implements delayed loading based on the proxy mode to save memory. However, if an object needs to be used in multiple places without a fixed time series, it must be empty, it will also sacrifice performance to some extent (a bit like proxy mode + lazy mode ). here is an example of renting a house.

Here, we assume that House is a very large object, which consumes resources during creation, so we can change it to initialization only when Custom needs to use it. in this case, when constructing the ProxyHouse, determine whether the House reference is null before initializing the House, of course, if multithreading concurrency exists here, you can apply locks or double check locks based on different scenarios to ensure thread security.

 

    public ProxyHouse(){        if (null == house)            house = new House(Downton Abbey, 5000);    }
        IHouse proxyHouse = new ProxyHouse();        Log.i(TAG, looking for a perfect house);        proxyHouse.getHouseInfo();        Log.i(TAG, thinking);        proxyHouse.signContract();        proxyHouse.payFees();        Log.i(TAG, so easy);
3. Force proxy

 

Force proxy is the opposite proxy mode. Generally, the proxy mode finds the real object through proxy, the forced proxy can be found through real objects, that is, the proxy is specified by the real object. Of course, the final access is still in the proxy mode. we can also see from the name that it is different from other proxies, that is, force the use of proxies. taking the example of the normal proxy above, Custom can only access the House through the proxy when it does not see the House of the entity. However, due to no restrictions, Custom can also directly bypass ProxyHouse to access the House, however, the mandatory proxy has one more limit. Custom must use ProxyHouse to access the House. just like some landlords are too troublesome. Some tenants directly call us to visit the house. The landlord gives an intermediary phone number to say that you have contacted the intermediary.

First, you must add an interface to obtain the proxy.

public interface IHouse {    void getHouseInfo();    void signContract();    void payFees();    IHouse getProxy();}
Real Object implementation interface, instantiate proxy in getProxy, and make proxy judgment in other methods. Only self-defined proxy can be used normally.

 

public class House implements IHouse{    private final String TAG = House.class.getSimpleName();    private String name;    private double price;    private IHouse proxy;    public House(String name, double price){        this.name = name;        this.price = price;    }    @Override    public void getHouseInfo() {        if (isProxy())            Log.i(TAG, House Info- name: + name +   ¥: + price);        else            Log.i(TAG, Please use correct proxy);    }    @Override    public void signContract() {        if (isProxy())            Log.i(TAG, Contract: + name +   signed at +                    new SimpleDateFormat(HH:mm:ss).format(SystemClock.uptimeMillis()));        else            Log.i(TAG, Please use correct proxy);    }    @Override    public void payFees() {        if (isProxy())            Log.i(TAG, Bill: name- + name +   $- + price);        else            Log.i(TAG, Please use correct proxy);    }    @Override    public IHouse getProxy() {        if (null == proxy)            proxy = new ProxyHouse(this);        return proxy;    }    private boolean isProxy(){        if (null == proxy)            return false;        else            return true;    }}
If you directly operate the House object at this time or access the object through the proxy built by Custom, the following results will be returned:

 


Therefore, you must use the proxy specified by the real object to access the agent normally.

        IHouse house = new House(Downton Abbey, 5000);        house = house.getProxy();        Log.i(TAG, looking for a perfect house);        house.getHouseInfo();        Log.i(TAG, thinking);        house.signContract();        house.payFees();

However, the force proxy here has a Bug.In fact, the Force proxy does not take effect. Custom can still directly access the House. For example, if I access it in the following way, I only create and obtain the proxy through getProxy, however, I still directly use the House instance for access without proxy, and this can still be accessed normally. we will try to solve this Bug and update it later.

 

IHouse house = new House (Downton Abbey, 5000); house. getProxy (); // here, only the proxy Log is created through getProxy. I (TAG, looking for a perfect house); house. getHouseInfo (); Log. I (TAG, thinking); house. signContract (); house. payFees ();

 

4. Dynamic proxy

All of the above are the proxy classes that you have written first. In this way, the proxy relationships are fixed. When multiple real objects are managed in the contemporary era, multiple proxy classes will be written, and redundant code will be generated, the scalability and maintainability are not high, and dynamic proxy is based on reflection to determine what objects to proxy during the process of running the program. the core idea of AOP is dynamic proxy. (Java Dynamic proxy is used here)

 

Since a dynamic Proxy does not require ProxyHouse or IHouse interface, here we write a ProxyHandler to implement InvocationHandler's invoke interface, and provide a Proxy instance built based on the Proxy to Custom. print the method name before calling the actual object method through reflection.

public class ProxyHandler implements InvocationHandler{    private final String TAG = ProxyHandler.class.getSimpleName();    Object targetObj;    public Object newProxyInstance(Object targetObj){        this.targetObj = targetObj;        return Proxy.newProxyInstance(targetObj.getClass().getClassLoader(),                    targetObj.getClass().getInterfaces(), this);    }    @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        Object ret;        Log.i(TAG, method name: + method.getName());        ret = method.invoke(targetObj, args);        return ret;    }}
        ProxyHandler proxy = new ProxyHandler();        IHouse house = (IHouse) proxy.newProxyInstance(new House(Downton Abbey, 5000));        Log.i(TAG, looking for a perfect house);        house.getHouseInfo();        Log.i(TAG, thinking);        house.signContract();        house.payFees();        Log.i(TAG, so easy);
From the results, we can see that the method name is printed before the method of the real invoke object, and some other object control can be done here.

 


At this time, the sequence diagram of the entire process becomes the following. The core functions of dynamic Proxy are supported through the JDK Proxy object and reflection mechanism.

III. there are still many scenarios to summarize the proxy mode, which can reduce the complexity of objects and decouple projects (especially dynamic proxy AOP, the best way to learn the design pattern is to use it. You can use it flexibly when it is applicable to the pattern.

 

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.