1. 程式人生 > >代理模式及實現

代理模式及實現

loader 方法參數 測試 food err pro sta 控制 tcl

技術分享圖片

代理對象和委托對象繼承相同接口,並控制外部對委托對象的訪問。

1. 靜態代理: 代理對象在編譯期確定。

接口(Human):

public interface Human{
    public void eatFood();
}

委托類(HumanImpl):

public class HumanImpl implements Human{
    public void eatFood(){
        System.out.print("真香!");
    }
}

代理類(HumanProxy):

public class HumanProxy implements Human{
    
private Human human; public HumanProxy(Human human){ this.human = human; } public void eatFood(){ before(); human.eatFood(); after(); } }

2. 動態代理: 運行期生成代理對象

  在代理類和委托類之間生成中介類,該類實現 InvocationHandler 接口。對委托對象方法的調用會轉到中介對象的invoke()方法中,method標識了調用哪一個方法,args代表方法參數。

  不需要實現代理的接口。

public class HumanDynamicProxy implements InvocationHandler{
    //委托對象
    private Human human;
    public HumanDynamicProxy(Human human){
        this.human = human;
    }
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { before(); Object result
= method.invoke(human, args); after(); return result; } }

測試代碼:

public static void main(String[] args){
    //委托對象
    Human realHuman = new HumanImpl();
    //中介
    InvocationHandler  handler = new HumanDynamicProxy(human);
    //動態代理
    Human proxy = (Human) Proxy.newProxyInstance(realHuman.getClass().getClassLoader(), realhuman.getClass().getInterfaces(), handler);
    //通過代理類,執行方法;
    proxy.eatFood();

代理模式及實現