Android Design Patterns - Agent Patterns

Posted by railgun on Thu, 09 May 2019 05:06:04 +0200

1. definition

Providing a proxy for an object and controlling the reference of the original object by the proxy object is an object structural pattern.

2. role

In some cases, customers do not want or can not directly refer to an object, which can be indirectly referred to by a third party called a "proxy". Proxy objects can act as intermediaries between clients and target objects, and can remove content and services that customers cannot see through proxy objects, or add additional services that customers need.

3. role

  • Abstract theme roles: declare the common interface between real theme and proxy theme;
  • Proxy Theme Roles: It contains references to real themes and can manipulate real themes at any time.
  • Real Theme Roles: Define the real objects represented by proxy roles, implement real business operations in real theme roles, and clients can indirectly invoke the methods defined in real theme roles through proxy theme roles.

4. implementation

On holidays, train tickets are very difficult to buy, so a variety of ticket-grabbing software prevails. We give the information to the service providers, then the software helps us to brush tickets day and night, and eventually we will probably get tickets. Here, the person who provides ticket-snatching service is the agent, helping the buyer get commission for ticket-snatching. The person who buys tickets is the agent and has real demand for tickets.

Here is an example to illustrate the use of proxy mode.

The realization of agent is divided into:

  • Static proxy: The proxy class is completed at compile time. That is to say, the proxy class after Java compilation is an actual class file.
  • Dynamic proxy: Proxy classes are generated at runtime. That is to say, after Java compiles, there is no actual class file, but class bytecode generated dynamically at runtime and loaded into JVM.
class diagram

First, look at static proxy, which is easy to understand.

  1. Define abstract subject roles.
public interface ITicketBuyer {
    /**
     * Buy tickets
     */
    void buyTicket();
}

  1. Define the real subject role, that is, the person who needs to buy tickets.
public class RealBuyer implements ITicketBuyer {

    @Override
    public void buyTicket() {
        System.out.println("I'd like a business seat at Xingxing from Beijing to Shanghai.");
    }
}

  1. Define proxy theme roles, provide ticket-snatching service, and hold information about the ticket buyer.
public class ProxyBuyer implements ITicketBuyer {
    // The agent, the person who really wants to buy tickets
    private ITicketBuyer realBuyer;

    public ProxyBuyer(ITicketBuyer realBuyer) {
        this.realBuyer = realBuyer;
    }

    @Override
    public void buyTicket() {
        System.out.println("Agents buy tickets:");
        realBuyer.buyTicket();
    }
}

Dynamic proxy, creating proxy class dynamically, all methods of proxy object are forwarded to an object called InvocationHandler, at which time the proxy can be realized by calling the method of proxy object. For more knowledge of dynamic proxy, please refer to " Proxy Mode and Java Implementation of Dynamic Proxy」.

public class DynamicProxyBuyer implements InvocationHandler {
    // The agent, the person who really wants to buy tickets
    private ITicketBuyer ticketBuyer;

    public DynamicProxyBuyer(ITicketBuyer ticketBuyer) {
        this.ticketBuyer = ticketBuyer;
    }

    public ITicketBuyer createProxy() {
        return (ITicketBuyer) Proxy.newProxyInstance(ITicketBuyer.class.getClassLoader(), new Class[]{ITicketBuyer.class}, this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if ("buyTicket".equals(method.getName())) {
            System.out.println("Agents buy tickets:");
        }
        return method.invoke(ticketBuyer, args);
    }
}

When the client class is used, the method of the proxy object can be directly invoked to achieve the purpose of the proxy.

public class ProxyTest {

    public static void main(String[] args) {
        // Static proxy
        ITicketBuyer realBuyer = new RealBuyer();
        //ITicketBuyer proxyBuyer = new ProxyBuyer(realBuyer);
        //proxyBuyer.buyTicket();

        // Dynamic proxy
        DynamicProxyBuyer dynamicProxyBuyer = new DynamicProxyBuyer(realBuyer);
        ITicketBuyer proxyBuyer = dynamicProxyBuyer.createProxy();
        proxyBuyer.buyTicket();
    }
}

5. advantages and disadvantages

1. advantages:
Coordinating the caller and the callee reduces the coupling of the system; the proxy object acts as the intermediary between the client and the target object, and plays the role of protecting the target object.

2. disadvantages:
As proxy objects are added between the client and the real topic, the processing speed of requests will be slowed down.
Implementing proxy patterns requires additional work (some of which are very complex to implement), thus increasing the complexity of system implementation.

3. Use scenarios:
When it is necessary to control access to the original object; when it is necessary to create an object with high overhead; when additional operations are required to access the object.
[appendix]

Data map

Friends who need information can join the Android framework to exchange QQ group chats: 513088520

Click on the link to join the group chat [Android Mobile Architecture Group]: Join group chat

Get free learning videos, learning syllabus and Android high-level development materials such as advanced UI, performance optimization, architect courses, NDK, React Native + Weex, etc. are also free to share.

Topics: Java Android jvm Mobile