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

Notes on the Agent Pattern of Java Design Patterns

Oct 18, 2017 am 09:39 AM
java notes Design Patterns

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles