Java description design pattern (16): agent pattern

Keywords: Java github network Programming JDK

Source code: GitHub point here || GitEE point here

I. life scene

1. Scene description

Today, with the rapid development of e-commerce, the number of express delivery is very large, and even there is the express agent industry. Simply speaking, the owner of express delivery does not have time to receive express delivery, and will designate a collection point for express delivery, such as express cabinet, express post station, etc., and then pick it up when there is time. The following use code to briefly describe this scenario.

2. Scene illustration

3. Source code implementation

public class C01_InScene {
    public static void main(String[] args) {
        /*Test method of receiving express by yourself*/
        GetExpress getExpress = new GetExpress();
        getExpress.sureInfo();
        getExpress.signName("Zhang San");
        /*Test method of collecting Express*/
        ExpressAct getUser = new GetExpress();
        ExpressAct getProxy = new ProxyExpress(getUser);
        getProxy.sureInfo();
        getProxy.signName("Li Si");
    }
}
/**
 * Action interface for receiving express delivery: confirmation information, signature
 */
interface ExpressAct{
    void sureInfo();
    void signName(String name);
}
/**
 * Define a class to receive express: get express by yourself
 */
class GetExpress implements ExpressAct{
    @Override
    public void sureInfo() {
        System.out.println("Please confirm your personal information!");
    }
    @Override
    public void signName(String name) {
        System.out.println("Your name is:"+name);
    }
}
/**
 * Define a class of receiving express: find someone to collect Express
 */
class ProxyExpress implements ExpressAct{
    private ExpressAct expressAct=null;
    public ProxyExpress(ExpressAct expressAct){
        this.expressAct = expressAct;
    }
    @Override
    public void sureInfo() {
        this.expressAct.sureInfo();
    }
    @Override
    public void signName(String name) {
        this.expressAct.signName(name);
    }
}

II. Agency mode

1. Concept description

Proxy mode is the structural mode of an object. The proxy mode provides a proxy object for an object, and the proxy object controls the reference to the original object. The so-called agent is that one object executes the corresponding action program on behalf of another. The proxy object can mediate between the client and the target object.

2. Mode diagram

3. Core role

  • Abstract object role

Declare the common interface between the target object and the proxy object.

  • Target object role

Defines the target object represented by the proxy object.

  • Proxy object role

The proxy object contains the reference of the target object and can operate the target object at any time. The proxy object provides the same interface as the target object and can replace the target object at any time. The agent object usually performs an operation before or after the client call is passed to the target object, rather than simply passing the call to the target object. AOP programming is based on this idea.

4. Source code implementation

public class C02_Proxy {
    public static void main(String[] args) {
        AbstractObject object = new ProxyObject();
        object.operation();
    }
}
/**
 * Abstract object role
 */
abstract class AbstractObject{
    public abstract void operation();
}
/**
 * Target object role
 */
class TargetObject extends AbstractObject{
    @Override
    public void operation() {
        System.out.println("Target Method Run...");
    }
}
/**
 * Proxy object role
 */
class ProxyObject extends AbstractObject{
    TargetObject targetObject = new TargetObject();
    @Override
    public void operation() {
        System.out.println("Method Before...");
        targetObject.operation();
        System.out.println("Method After...");
    }
}

III. JDK dynamic agent

Based on JDK dynamic agent, AOP is implemented.

1. Code implementation

public class C03_JdkProxy {
    public static void main(String[] args) {
        BookService bookService = BookAopProxyFactory.createService() ;
        System.out.println(bookService.getBook());
    }
}
class BookAspect {
    public void before (){
        System.out.println("Method Before ...");
    }
    public void after (){
        System.out.println("Method After ...");
    }
}
interface BookService {
    String getBook () ;
}
class BookServiceImpl implements BookService {
    @Override
    public String getBook() {
        System.out.println("Target method[ getBook]Be executed");
        return "High performance MySQL";
    }
}
class BookAopProxyFactory {
    public static BookService createService() {
        // Target class
        final BookService bookService = new BookServiceImpl() ;
        // Section class
        final BookAspect bookAspect = new BookAspect();
        /*
         * Proxy class: combine the target class (pointcut) and the tangent class (notification)
         */
        BookService proxyBookService = (BookService) Proxy.newProxyInstance(
                BookAopProxyFactory.class.getClassLoader(),
                bookService.getClass().getInterfaces(),
                new InvocationHandler() {
                    public Object invoke(Object proxy, Method method,
                                         Object[] args) throws Throwable {
                        // Pre execution
                        bookAspect.before();
                        // Methods for executing target classes
                        Object obj = method.invoke(bookService, args);
                        // Post execution
                        bookAspect.after();
                        return obj;
                    }
                });
        return proxyBookService ;
    }
}

IV. several common agents

  • Firewall agent

The internal network through the proxy through the firewall, to achieve access to the public network.

  • Cache proxy

In order to alleviate the concurrent pressure of the website, when requesting the database resources, first fetch the data of the proxy in the cache. If the cache fails to hit, then fetch the data from the database, and then cache the retrieved data.

  • Remote agent

The local proxy object of the remote object, through which the remote object can be called as a local object. The remote agent interacts with the called remote object through the network.

  • Synchronous proxy

It is mainly used in multithreading programming to complete the synchronization among multithreads.

V. source code address

GitHub·address
https://github.com/cicadasmile/model-arithmetic-parent
GitEE·address
https://gitee.com/cicadasmile/model-arithmetic-parent

Posted by DarkShadowWing on Tue, 29 Oct 2019 09:35:43 -0700