代理模式是一种常见的设计模式,它允许一个对象在不改变其行为的情况下,控制对另一个对象的访问。代理模式通常用于保护敏感对象,或者为了延迟实际对象的加载。
在Java中,代理模式有两种形式:静态代理和动态代理。静态代理需要手动编写代理类,而动态代理则可以在运行时自动生成代理类。
示例代码:静态代理
public interface UserService {
void save(String name);
}
public class UserServiceImpl implements UserService {
@Override
public void save(String name) {
System.out.println("保存用户:" + name);
}
}
public class UserServiceProxy implements UserService {
private UserService userService;
public UserServiceProxy(UserService userService) {
this.userService = userService;
}
@Override
public void save(String name) {
System.out.println("开始事务");
userService.save(name);
System.out.println("提交事务");
}
}
public class Test {
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
UserService userServiceProxy = new UserServiceProxy(userService);
userServiceProxy.save("张三");
}
}
示例代码:动态代理
public interface UserService {
void save(String name);
}
public class UserServiceImpl implements UserService {
@Override
public void save(String name) {
System.out.println("保存用户:" + name);
}
}
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("开始事务");
Object result = method.invoke(target, args);
System.out.println("提交事务");
return result;
}
}
public class Test {
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
MyInvocationHandler invocationHandler = new MyInvocationHandler(userService);
UserService userServiceProxy = (UserService) Proxy.newProxyInstance(UserService.class.getClassLoader(),
new Class[]{UserService.class}, invocationHandler);
userServiceProxy.save("张三");
}
}
动态代理是通过Java提供的Proxy类和InvocationHandler接口来实现的。相较于静态代理,动态代理更加灵活,因为它可以在运行时生成代理类,并且可以代理任何实现了接口的类,而不需要手动编写代理类。
标签:name,对象,代理,访问,UserService,userService,save,public From: https://www.cnblogs.com/li053/p/17465385.html