代理模式 - Proxy Pattern
- 在代理模式(Proxy Pattern)中,一個類代表另一個類的功能。這種類型的設(shè)計(jì)模式屬于結(jié)構(gòu)型模式。
- 在代理模式中,我們創(chuàng)建具有現(xiàn)有對象的對象,以便向外界提供功能接口。
-
意圖: 為其他對象提供一種代理以控制對這個對象的訪問。
目前有一個現(xiàn)有的業(yè)務(wù)邏輯 并 有實(shí)現(xiàn)邏輯
public interface Product {
void createProduct();
}
public class ProductLevel implements Product {
@Override
public void createProduct() {
System.out.println("創(chuàng)建一個項(xiàng)目");
}
}
定義一個動態(tài)代理類
public class JDKDynamicProxy implements InvocationHandler {
/**
* 聲明被代理的對象
*/
private Product product;
public JDKDynamicProxy(Product product) {
this.product = product;
}
public Object getTarget() {
return Proxy.newProxyInstance(product.getClass().getClassLoader(), product.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("增加執(zhí)行代理對象之前的邏輯");
method.invoke(product, args);
System.out.println("增加執(zhí)行代理對象之后的邏輯");
return null;
}
}
調(diào)用
public static void main(String[] args) {
System.out.println("不使用代理模式");
Product product = new ProductLevel();
product.createProduct();
System.out.println("---------------------");
System.out.println("使用代理模式");
Product proxy = (Product) new JDKDynamicProxy(new ProductLevel()).getTarget();
proxy.createProduct();
}
輸出
不使用代理模式
創(chuàng)建一個項(xiàng)目
---------------------
使用代理模式
增加執(zhí)行代理對象之前的邏輯
創(chuàng)建一個項(xiàng)目
增加執(zhí)行代理對象之后的邏輯
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。