1. 程式人生 > 其它 >Java設計模式-動態代理

Java設計模式-動態代理

技術標籤:Java設計模式java

房屋出租案例(實現動態代理)

(InvocationHandler介面:呼叫處理程式)

(Proxy類:生成代理)

1.房東

package com.lit.demo;

public interface rent {
    public void rent();
}

package com.lit.demo;

public class hots implements rent {
    public void rent() {
        System.out.println("房東要出租房子!");
    }
}

2.中介(代理)

package com.lit.demo;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//自動代理類
public class ProxyInvocation implements InvocationHandler {
    //被代理的介面
    private rent rent;
    public void setRent(rent rent) {
        this.rent =
rent; } //生成得到代理類 public Object getProxy(){ Object o = Proxy.newProxyInstance(this.getClass().getClassLoader(), rent.getClass().getInterfaces(), this); return o; } //處理代理例項並返回結果 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { see
(); //動態代理的本質就是使用反射 Object result = method.invoke(rent, args); fare(); return result; } public void see(){ System.out.println("中介帶著看房子!"); } public void fare(){ System.out.println("收租金!"); } }

3.客戶

package com.lit.demo;

public class client {
    public static void main(String[] args) {
        //真實角色
        hots hots = new hots();
        //代理角色 現在沒有
        ProxyInvocation proxy = new ProxyInvocation();
        //通過呼叫程式處理角色來處理我們要呼叫的介面物件!
        proxy.setRent(hots);
        rent p = (rent) proxy.getProxy();
        p.rent();
    }
}