Home Java javaTutorial An example of Java using the proxy pattern in design pattern to build a project

An example of Java using the proxy pattern in design pattern to build a project

Feb 07, 2017 pm 01:26 PM

Concept

Proxy mode (Proxy): The proxy mode is actually an additional proxy class that performs some operations on behalf of the original object. For example, sometimes we need to hire a lawyer when we go to court, because lawyers have expertise in law and can express our ideas on our behalf. This is what agency means. The proxy mode is divided into two categories: 1. Static proxy (does not use the methods in jdk); 2. Dynamic proxy (uses InvocationHandler and Proxy in jdk).
Static agents are created by programmers or tools generate the source code of the agent class, and then compile the agent class. The so-called static means that the bytecode file of the proxy class already exists before the program is run, and the relationship between the proxy class and the delegate class is determined before running.
The source code of the dynamic proxy class is dynamically generated by the JVM based on mechanisms such as reflection during program running, so there is no bytecode file for the proxy class. The relationship between the proxy class and the delegate class is determined when the program is running.

Example
Here we give an example of a static proxy:
Class diagram:

An example of Java using the proxy pattern in design pattern to build a project

/** 
 * 游戏者接口 
 * 
 */
public interface IGamePlayer { 
  
  // 登录游戏 
  public void login(String user, String password); 
  
  // 杀怪,网络游戏的主要特色 
  public void killBoss(); 
  
  // 升级 
  public void upgrade(); 
  
}
Copy after login
/** 
 * 游戏者 
 * 
 */
public class GamePlayer implements IGamePlayer { 
  
  private String name = ""; 
  
  // 通过构造函数传递名称 
  public GamePlayer(String _name) { 
    this.name = _name; 
  } 
  
  // 打怪,最期望的就是杀老怪 
  
  public void killBoss() { 
  
    System.out.println(this.name + " 在打怪!"); 
  
  } 
  
  // 进游戏之前你肯定要登录吧,这是一个必要条件 
  public void login(String user, String password) { 
    System.out.println("登录名为" + user + " 的角色 " + this.name + "登录成功!"); 
  } 
  
  // 升级,升级有很多方法,花钱买是一种,做任务也是一种 
  public void upgrade() { 
    System.out.println(this.name + " 又升了一级!"); 
  } 
  
}
Copy after login
/** 
 * 客户端 对被代理对象不可见 
 */
public class GamePlayerProxy implements IGamePlayer { 
  
  private IGamePlayer gamePlayer = null;//被代理对象 
  
  // 通过构造函数传递要对谁进行代练 
  public GamePlayerProxy(String username) { 
    this.gamePlayer = new GamePlayer(username); 
  } 
  
  // 代练杀怪 
  public void killBoss() { 
    this.gamePlayer.killBoss(); 
  } 
  
  // 代练登录 
  public void login(String user, String password) { 
    this.gamePlayer.login(user, password); 
  } 
  
  // 代练升级 
  public void upgrade() { 
    this.gamePlayer.upgrade(); 
  } 
  
}
Copy after login
/* 
 * 客户端 对被代理对象不可见 
 */
public class GamePlayerProxy2 implements IGamePlayer { 
  
  private IGamePlayer gamePlayer = null;//被代理对象 
  
  // 通过构造函数传递要对谁进行代练 
  public GamePlayerProxy2(String username) { 
    this.gamePlayer = new GamePlayer(username); 
  } 
  
  // 代练杀怪 
  public void killBoss() { 
    this.gamePlayer.killBoss(); 
  } 
  
  // 代练登录 
  public void login(String user, String password) { 
    System.out.println("登录时间是:" + new Date().toLocaleString()); 
    this.gamePlayer.login(user, password); 
  } 
  
  // 代练升级 
  public void upgrade() { 
    this.gamePlayer.upgrade(); 
    System.out.println("升级时间是:" + new Date().toLocaleString()); 
  } 
  
}
Copy after login
/* 
 * 客户端 对被代理对象不可见 
 */
public class GamePlayerProxy3 { 
  
  private IGamePlayer gamePlayer; 
  // 通过构造函数传递 被代练(代理)对象 
  public GamePlayerProxy3(IGamePlayer gamePlayer) { 
     this.gamePlayer = gamePlayer; 
     System.out.println("我是一名代练,我玩的角色是别人的,可以动态传递进来"); 
  } 
    
  public IGamePlayer getProxy() { 
    return (IGamePlayer) Proxy.newProxyInstance(this.getClass().getClassLoader(),  
        new Class[]{IGamePlayer.class}, new MyInvocationHandler()); 
  } 
  
  private class MyInvocationHandler implements InvocationHandler { 
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 
      if (method.getName().equals("login")) { 
        System.out.println("登录时间是:" + new Date().toLocaleString()); 
      } if (method.getName().equals("upgrade")) { 
        System.out.println("升级时间是:" + new Date().toLocaleString()); 
      } 
      method.invoke(gamePlayer, args); 
      return null; 
    } 
      
  } 
}
Copy after login
public class Test { 
  public static void main(String[] args) { 
    /* 
     * 普通的静态代理: 客户端不知道被代理对象,由代理对象完成其功能的调用 
     */ 
    IGamePlayer proxy = new GamePlayerProxy("X"); 
    System.out.println("开始时间是:" + new Date().toLocaleString()); 
    proxy.login("zhangSan", "abcd"); 
    proxy.killBoss(); 
    proxy.upgrade(); 
    System.out.println("结束时间是:" + new Date().toLocaleString()); 
      
    System.out.println(); 
      
    /* 
     * 代理对象 增强了 被代理对象的功能 
     */ 
    IGamePlayer proxy2 = new GamePlayerProxy2("M"); 
    proxy2.login("lisi", "efg"); 
    proxy2.killBoss(); 
    proxy2.upgrade(); 
      
    System.out.println(); 
      
    /* 
     * 动态代理:使用jdk提供的InvocationHandler,反射调用被代理对象的方法 
     * 结合java.reflect.Proxy 产生代理对象 
     * 动态传入被代理对象构造InvocationHandler,在handler中的invoke时可以增强被代理对象的方法的功能 
     * 或者说:(面向切面:)在什么地方(连接点), 执行什么行为(通知) 
     * GamePlayerProxy3中是方法名为login时通知开始时间,upgrade时通知结束时间 
     */ 
    GamePlayerProxy3 dynamic = new GamePlayerProxy3(new GamePlayer("Y")); 
    IGamePlayer dynamicPlayer = dynamic.getProxy(); 
    dynamicPlayer.login("wangwu", "1234"); 
    dynamicPlayer.killBoss(); 
    dynamicPlayer.upgrade(); 
    /* 
     * 面向切面: 一些相似的业务逻辑需要加在众多的地方,那们就可以把它提取到切面中, 切面也就是事务切面:如日志切面、权限切面、业务切面 
     */
  } 
}
Copy after login

Print:

开始时间是:2014-10-8 17:19:05 
登录名为zhangSan 的角色 X登录成功! 
X 在打怪! 
X 又升了一级! 
结束时间是:2014-10-8 17:19:05 
  
登录时间是:2014-10-8 17:19:05 
登录名为lisi 的角色 M登录成功! 
M 在打怪! 
M 又升了一级! 
升级时间是:2014-10-8 17:19:05 
  
我是一名代练,我玩的角色是别人的,可以动态传递进来 
登录时间是:2014-10-8 17:19:05 
登录名为wangwu 的角色 Y登录成功! 
Y 在打怪! 
升级时间是:2014-10-8 17:19:05 
Y 又升了一级!
Copy after login

Advantages
(1) Clear responsibilities
The real role is to implement the actual business logic. You don’t need to care about other matters that are not your responsibilities. You can complete a completed transaction through the later agent. The accompanying result is that the programming is simple and clear.
(2) The proxy object can play an intermediary role between the client and the target object, which plays a role in protecting the target object.
(3) High scalability

For more examples of Java using the proxy pattern in design patterns to build projects, please pay attention to the PHP Chinese website for related articles!

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)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles