在代理模式(Proxy Pattern)中,一個類代表另一個類的功能。這種類型的設計模式屬於結構型模式。在代理模式中,我們創建具有現有對象的對象,以便向外界提供功能接口。
1.靜態代理
1.1 定義接口
/**
* 接口
*/
public interface UserService {
/**
* 添加方法
*/
void add();
/**
* 刪除方法
*/
void delete();
}
1.2 實現接口類
/**
* 接口實現類
*/
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("--------------------add---------------");
}
@Override
public void delete() {
System.out.println("--------------------delete---------------");
}
}
1.3 代理類
/**
* 代理類
*/
public class StaticProxy implements UserService {
UserService userService;
public StaticProxy(UserServiceImpl userService){
this.userService=userService;
}
@Override
public void add() {
userService.add();
System.out.println("這是代理類做的事");
}
@Override
public void delete() {
userService.delete();
}
}
1.4 測試靜態代理
public class StaticTest {
@Test
public void test1(){
UserService userService=new StaticProxy(new UserServiceImpl());
userService.add();
}
}
2.動態代理
2.1 動態代理
/**
* 實現自己的InvocationHandler
*/
public class MyInvocationHandler implements InvocationHandler {
private static Object target;
/**
* 執行目標對象的方法
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 在目標對象的方法執行之前簡單的打印一下
System.out.println("這是代理類做的事A");
// 執行目標對象的方法
Object result = method.invoke(target, args);
// 在目標對象的方法執行之後簡單的打印一下
System.out.println("這是代理類做的事B");
return result;
}
/**
* 獲取目標對象的代理對象
*
* @return 代理對象
*/
public static Object getProxy(Object target) {
MyInvocationHandler.target=target;
return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), target.getClass().getInterfaces(), new MyInvocationHandler());
}
}
2.2測試
/**
* 動態代理
*/
public class ProxyTest {
@Test
public void testProxy() throws Throwable {
// 實例化目標對象
UserServiceImpl userService=new UserServiceImpl();
// 根據目標對象生成代理對象
UserService proxy = (UserService) MyInvocationHandler.getProxy(userService);
// 調用代理對象的方法
proxy.add();
}
}