Dynamic proxy mode of java design pattern

Dynamic proxy mode

Provides a proxy for an object to control access to this object.

accomplish

This example illustrates the borrowing and collection of the correspondent bank

code

package com.test;

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

//第1步,银行的借款和收款接口业务接口
interface IBank {

    void jiekuan();

    void shoukuan();
}

// 第2步, 代理人,代理银行的借款收款业务
class Person implements IBank {

    @Override
    public void jiekuan() {
        System.out.println("向银行借款");
    }

    @Override
    public void shoukuan() {
        System.out.println("还款给银行");
    }
}

// 第3步,代理类,需要实现InvocationHandler 接口
class MyInvokeHandler implements InvocationHandler {
    private Object realObject;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (realObject == null)
            return null;
        return method.invoke(realObject, args);
    }

    public Object getRealObject(Object realObject) {
        if (realObject == null)
            return null;
        this.realObject = realObject;
        Class c = realObject.getClass();
        return Proxy.newProxyInstance(c.getClassLoader(), c.getInterfaces(), this);
    }
}

// 第4步,实现代理

public class Test {
    public static void main(String[] args) {
        Person p = new Person();
        MyInvokeHandler myInvokeHandler = new MyInvokeHandler();
        // 为Person对象p提供代理
        IBank iBank = (IBank) myInvokeHandler.getRealObject(p);
        // 控制其的真实访问
        iBank.jiekuan();
        iBank.shoukuan();
    }

}

operation result:

The actual execution is the method of the Person object

向银行借款
还款给银行

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324823818&siteId=291194637