Home > Java > javaTutorial > Notes on the Agent Pattern of Java Design Patterns

Notes on the Agent Pattern of Java Design Patterns

黄舟
Release: 2017-10-18 09:39:00
Original
1181 people have browsed it

This article mainly introduces the proxy mode notes of Java design pattern in detail, which has certain reference value. Interested friends can refer to

Proxy (Proxy) mode:

The proxy pattern is the structural pattern of objects. The proxy pattern provides a proxy object for an object, and the proxy object controls the reference to the original object.

Core function:

Control access to objects through proxies.

You can control the method of accessing a certain (certain type of) object in detail, do pre-processing before calling this method, and do post-processing after calling this method. That is, the micro implementation of AOP.

The core implementation mechanism of AOP (Aspect Oriented Programming).

Scenes in life:

The so-called agency is a person or institution taking action on behalf of another person or institution. In some cases, a client does not want or cannot reference an object directly, and a proxy object can act as an intermediary between the client and the target object.
For example, if a client wants to find a star to sing, he first needs to find his agent, and then his agent will arrange for the star to sing.
The agent needs to handle some pre-processing before the concert (interviews, contract drafting, signing, collecting advance payment, arranging air tickets and vehicles, etc.) and needs to handle some post-processing (closing payment, etc.) after the concert is held. . At this time, a certain star (real character) only needs to care about how to sing, and all other matters are left to the manager (agent).

Core role:

Write picture description here

Abstract object role: declares the common interface between the proxy object and the real object, defines the proxy object and Public external methods of real objects. This allows the proxy object to be used anywhere a real object can be used.

Real object role: Defines the real object represented by the proxy object. Implement abstract objects and define the business logic that needs to be implemented by real objects for calls by proxy objects. Focus on real business logic.

Proxy object role: implements abstract objects and is a proxy for real objects. It implements abstract methods through the business logic methods of real objects and attaches its own operations. Put unified process control into proxy objects.

The proxy object contains a reference to the real object internally, so that the real object can be operated at any time; the proxy object provides an interface identical to the real object, so that the real object can be replaced at any time. The proxy object usually performs an operation before or after the client call is passed to the real object, rather than simply passing the call to the real object.

Application scenarios:

Security proxy: Shield direct access to real roles.
Remote proxy: handle remote method calls through proxy classes.
Lazy loading: Load the lightweight proxy object first, and then load the real object when needed. (Lazy loading of images)

Category:

Static proxy: (statically defined proxy class)

Code for the above example:

1. Declares the common interface between the proxy object and the real object, and defines the public external methods of the proxy object and the real object.


public interface Star {
  /**
   * 面谈
   */
  void confer();
  /**
   * 签合同
   */
  void signContract();
  /**
   * 订票
   */
  void bookTicket();
  /**
   * 唱歌
   */
  void sing();
  /**
   * 收钱
   */
  void collectMoney();
}
Copy after login
Copy after login

2. Define a real object class and implement the methods provided by the abstract interface.


public class RealStar implements Star {

  @Override
  public void bookTicket() {
    System.out.println("RealStar.bookTicket()");
  }

  @Override
  public void collectMoney() {
    System.out.println("RealStar.collectMoney()");
  }

  @Override
  public void confer() {
    System.out.println("RealStar.confer()");
  }

  @Override
  public void signContract() {
    System.out.println("RealStar.signContract()");
  }

  @Override
  public void sing() {
    System.out.println("RealStar.sing()");
  }
}
Copy after login
Copy after login

3. Define a proxy object class, implement the methods provided by the abstract interface, and hold a reference to the real object.


public class ProxyStar implements Star{

private Star star;

  public ProxyStar(Star star) {
    super();
    this.star = star;
  }

  @Override
  public void bookTicket() {
    System.out.println("ProxyStar.bookTicket()");
  }

  @Override
  public void collectMoney() {
    System.out.println("ProxyStar.collectMoney()");
  }

  @Override
  public void confer() {
    System.out.println("ProxyStar.confer()");
  }

  @Override
  public void signContract() {
    System.out.println("ProxyStar.signContract()");
  }

  @Override
  public void sing() {
    star.sing();
  }

}
Copy after login

4. Test class


public class Client {
  public static void main(String[] args) {
    //定义真实对象角色
    Star realStar = new RealStar();
    //定义代理对象角色,内部含有真实对象的引用
    Star proxyStar = new ProxyStar(realStar);

    proxyStar.confer();
    proxyStar.signContract();
    proxyStar.bookTicket();
    proxyStar.sing();
    proxyStar.collectMoney();

  }
}
Copy after login

The running results are as follows:


ProxyStar.confer()
ProxyStar.signContract()
ProxyStar.bookTicket()
RealStar.sing()
ProxyStar.collectMoney()
Copy after login

From the above example, we can see that the proxy object delegates the client's call to the real object, and can perform specific operations before and after calling the method of the target object.

Dynamic proxy: (dynamically generated proxy class):

Advantages of dynamic proxy compared to static proxy:

Abstract role All methods declared (interface) are transferred to a centralized method of calling the server for processing, so that we can handle numerous methods more flexibly and uniformly.

Dynamic proxy that comes with JDK

java.lang.reflect.Proxy
Dynamic generation of proxy classes and objects

java.lang.reflect.InvocationHandler (processor interface)
Proxy access to real roles can be achieved through the invoke method

Generate a proxy class through Proxy each time The corresponding processor object must be specified when object

The test code is as follows:

1. Declares the common interface of the proxy object and the real object, and defines the public external methods of the proxy object and the real object.


public interface Star {
  /**
   * 面谈
   */
  void confer();
  /**
   * 签合同
   */
  void signContract();
  /**
   * 订票
   */
  void bookTicket();
  /**
   * 唱歌
   */
  void sing();
  /**
   * 收钱
   */
  void collectMoney();
}
Copy after login
Copy after login

2. Define a real object class and implement the methods provided by the abstract interface.


public class RealStar implements Star {

  @Override
  public void bookTicket() {
    System.out.println("RealStar.bookTicket()");
  }

  @Override
  public void collectMoney() {
    System.out.println("RealStar.collectMoney()");
  }

  @Override
  public void confer() {
    System.out.println("RealStar.confer()");
  }

  @Override
  public void signContract() {
    System.out.println("RealStar.signContract()");
  }

  @Override
  public void sing() {
    System.out.println("RealStar.sing()");
  }
}
Copy after login
Copy after login

3. Define a StarHandler class to implement the InvocationHandler processor interface. You can achieve proxy access to the real role through the invoke method, and you can also perform many operations in the invoke method. Unified processing.


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class StarHandler implements InvocationHandler{

  private Star realStar;

  public StarHandler(Star realStar) {
    super();
    this.realStar = realStar;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args)
      throws Throwable {
    //返回值
    Object object = null;

    System.out.println("真正的方法执行前!");
    System.out.println("面谈,签合同,预付款,订机票");

    if(method.getName().equals("sing")){
      object = method.invoke(realStar, args);
    }

    System.out.println("真正的方法执行后!");
    System.out.println("收尾款");
    return object;

  }

}
Copy after login

4.客户端测试类


import java.lang.reflect.Proxy;

public class Client {

public static void main(String[] args) {

    Star realStar = new RealStar();
    StarHandler handler = new StarHandler(realStar);

    //通过Proxy生成代理类对象并指定对应的处理器对象
    Star proxyStar = (Star)Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), 
        new Class[]{Star.class}, handler);

    proxyStar.sing();

  }
Copy after login

运行结果如下:

真正的方法执行前!
面谈,签合同,预付款,订机票
RealStar.sing()
真正的方法执行后!
收尾款

开发框架中的应用场景

代理模式在开发框架中的应用场景是非常多的,实际上随便选择一个开发框架都有用到代理模式。例如:

mybatis中实现拦截器插件
AspectJ的实现
spring中AOP的实现

The above is the detailed content of Notes on the Agent Pattern of Java Design Patterns. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template