Home >Java >javaTutorial >Example explanation of proxy pattern in java design pattern
The following editor will bring you an article about java design pattern-agent pattern (explanation with examples). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
The proxy pattern is one of the most common design patterns in Java. Spring's aop uses the proxy mode.
Generally speaking, the proxy mode is divided into two types: static proxy and dynamic proxy.
As a design pattern for structural classes, its function is to extend the class without modifying the internal code of the class, which is a supplement to the inheritance mechanism.
eg: Let’s implement the proxy mode using the example of user login.
The basic requirement is to realize the user's login and nickname modification functions.
The code starts with the IUser interface and user implementation class
public interface IUser { //登录 void login(String userId,String password); //修改昵称 void editNickname(String nickname); }
public class User implements IUser { private String nickname; private String userId; private String password; public User(String userId,String password){ this.userId = userId; this.password = password; } @Override public void login(String userId, String password){ if(this.userId == userId && this.password == password){ System.out.println("用户登录成功"); } else System.out.println("用户登录失败"); } @Override public void editNickname(String nickname) { this.nickname = nickname; System.out.println("修改昵称成功,当前用户的昵称是:"+this.nickname); } }
Client class
public class Client { public static void main(String[] args) { //不调用代理模式时 IUser user = new User("firs","123"); user.login("firs", "123"); user.editNickname("大风"); }
It’s still very simple. But later the product manager tells you that we need to add a function to record user behavior. What should we do now? Directly modify the user class? No, no, no, use proxy mode.
Just add a proxy class and write the function of "recording user behavior" in the proxy class. Do not modify the class, just extend the class to reduce errors.
import java.util.Date; import java.util.HashMap; import java.util.Map; /** * 静态代理类必须实现接口,而且需要新创建一个类的代码出来 * @author Administrator * */ public class StaticProxy implements IUser { private IUser user; public StaticProxy(String userId,String password){ this.user = new User(userId,password); } //登陆前的操作,记录当前登录的时间 void noteLoginInfo(String[] params, String opreate){ Map<String,Object> loginInfo = new HashMap<>(); loginInfo.put("params", params); loginInfo.put("opreate", opreate); loginInfo.put("opreateTime", new Date()); System.out.println("记录用户操作成功"); } @Override public void login(String userId, String password){ noteLoginInfo(new String[]{userId, password},"login"); user.login(userId, password); } @Override public void editNickname(String nickname) { noteLoginInfo(new String[]{nickname},"editNickname"); user.editNickname(nickname); } }
Client class:
public class Client { public static void main(String[] args) { //不调用代理模式时 IUser user = new User("firs","123"); user.login("firs", "123"); user.editNickname("大风"); System.out.println(""); System.out.println("=============调用静态代理模式后==========="); //需要实现记录用户登录和修改昵称操作的日志功能 //基于“拓展开发,修改关闭”的设计准则,我们可以用静态代理的方式 IUser proxy = new StaticProxy("firs","123"); proxy.login("firs", "123"); proxy.editNickname("我还是大风"); }
In this way, you only need to modify the client class and add a static proxy. Yes, perfectly realized. But the demand is endless. The product manager tells you: "We have added an administrator role, and a second-level administrator." There are a lot of roles,
This is embarrassing, every time A static proxy class must be built for each character, and the classes will explode. Don't worry, we have dynamic proxy mode.
The dynamic proxy mode is that you do not need to create a new proxy class yourself. You pass the specific implementation class (subject) to it, and it will generate a proxy class for you by default.
Essentially, it uses Java's reflection mechanism to dynamically generate the corresponding proxy class at runtime.
Without reflection, there is no dynamic proxy.
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * 动态代理类不用和主体类继承同一个接口 * @author Administrator * */ public class DynamicProxy implements InvocationHandler { private Object object; public DynamicProxy(String userId,String password,Class<?> c){ Object obj = null; try { obj = Class.forName(c.getName()) .getConstructor(String.class,String.class) .newInstance(userId,password); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } this.object = obj; } //登陆前的操作,记录当前登录的时间 void noteLoginInfo(String[] params, String opreate){ Map<String,Object> loginInfo = new HashMap<>(); loginInfo.put("params", params); loginInfo.put("opreate", opreate); loginInfo.put("opreateTime", new Date()); System.out.println("记录用户操作成功"); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String[] params = new String[args.length]; for(int i = 0 ;i < args.length ; i++){ params[i] = args[i].toString(); } noteLoginInfo(params, method.getName()); return method.invoke(object, args); } }
The last client class:
package com.test.my; import java.lang.reflect.Proxy; public class Client { public static void main(String[] args) { //不调用代理模式时 IUser user = new User("firs","123"); user.login("firs", "123"); user.editNickname("大风"); System.out.println(""); System.out.println("=============调用静态代理模式后==========="); //需要实现记录用户登录和修改昵称操作的日志功能 //基于“拓展开发,修改关闭”的设计准则,我们可以用静态代理的方式 IUser proxy = new StaticProxy("firs","123"); proxy.login("firs", "123"); proxy.editNickname("我还是大风"); System.out.println(""); System.out.println("=============调用动态代理模式后==========="); DynamicProxy dynamicProxy = new DynamicProxy("firs","123",Admin.class); ClassLoader cl = Admin.class.getClassLoader(); IUser iuser = (IUser)Proxy.newProxyInstance(cl, new Class[]{IUser.class}, dynamicProxy); iuser.login("firs","123"); iuser.editNickname("使用动态代理后的大风"); } }
Admin class added due to demand
public class Admin implements IUser { private String nickname; private String userId; private String password; public Admin(String userId,String password){ this.userId = userId; this.password = password; } @Override public void login(String userId, String password){ if(this.userId == userId && this.password == password){ System.out.println("用户登录成功"); } else System.out.println("用户登录失败"); } @Override public void editNickname(String nickname) { this.nickname = nickname; System.out.println("修改昵称成功,当前用户的昵称是:"+this.nickname); } }
Summary:
1. The static proxy mode is relatively simple. The key point is that for each implementation class ( subject) creates a new proxy class, which has a reference to the entity class (subject), so that it can control the original implementation class (subject), including aop control, etc.
2. Static proxy has limitations. It may be necessary to create a new static proxy class for each entity class. This may cause too many static proxy classes, so dynamic proxy came into being. .
3. Dynamic proxy is not limited to the specific implementation class (subject body). Internally, it uses object to access the reference of the entity class, and then uses reflection to obtain various methods of the entity class, thereby realizing the Implement aspect-oriented AOP programming control of the class (subject body).
4. The above writing method is a dynamic proxy in JDK, which is not perfect because this kind of dynamic proxy requires the entity class to implement at least one interface. The problem is that not all classes will have interfaces, so it's not perfect here.
The above is the detailed content of Example explanation of proxy pattern in java design pattern. For more information, please follow other related articles on the PHP Chinese website!