基于反射实现的动态代理设计模式

package FanShe_Factory;

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


interface ISubject2{//核心操作接口
    public void eat(String foodname,int num) ;
}

class RealSubject2 implements ISubject2{

    @Override
    public void eat(String foodname, int num) {
        System.out.println("我要吃"+num+"斤的"+foodname);    
    }
}

class ProxySubject2 implements InvocationHandler{
    //传入真实业务类
    private Object realsubject;
    //将真实业务类与代理类绑定
    public Object bind(Object realsubject ) {
        this.realsubject=realsubject;
        return Proxy.newProxyInstance(realsubject.getClass().getClassLoader(), 
                                                                realsubject.getClass().getInterfaces(), this);    
    }
    public void before() {
        System.out.println("代理类处理前");
    }
    public void after() {
        System.out.println("代理类处理后");
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        this.before();
        Object ret=method.invoke(this.realsubject, args);
        this.after();
        return ret;
    }
    
}

public class FanShe_DongTaiDaiLi {
    public static void main(String[] args) {
        ISubject2 iSubject=(ISubject2) new ProxySubject2().bind(new RealSubject2());
        iSubject.eat("肉", 1);
    }

}
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值