An example of Java using the proxy pattern in design pattern to build a project
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:
/** * 游戏者接口 * */ public interface IGamePlayer { // 登录游戏 public void login(String user, String password); // 杀怪,网络游戏的主要特色 public void killBoss(); // 升级 public void upgrade(); }
/** * 游戏者 * */ 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 + " 又升了一级!"); } }
/** * 客户端 对被代理对象不可见 */ 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(); } }
/* * 客户端 对被代理对象不可见 */ 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()); } }
/* * 客户端 对被代理对象不可见 */ 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; } } }
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(); /* * 面向切面: 一些相似的业务逻辑需要加在众多的地方,那们就可以把它提取到切面中, 切面也就是事务切面:如日志切面、权限切面、业务切面 */ } }
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 又升了一级!
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!

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.