代理模式笔记

本文介绍了一个Java实现的Proxy设计模式,通过MyInvocationHandler创建SuperMan的代理对象,展示如何动态拦截并修改SuperMan的行为。重点在于`Human`接口、`MyInvocationHandler`和`ProxyFactory`的交互,以及在`SuperMan`中体现的实际应用。
摘要由CSDN通过智能技术生成
public interface Human {
    public String getBelief();
    void eat(String food);
}
public class MyInvocationHandler implements InvocationHandler {

    private Object object;
    public void bind(Object o) {
        this.object=o;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object returnvalue=method.invoke(object,args);
        return returnvalue;
    }
}
public class ProxyFactory {
    public static Object getProxyInstance(Object o){
        MyInvocationHandler handler=new MyInvocationHandler();
        handler.bind(o);
        return Proxy.newProxyInstance(o.getClass().getClassLoader(),o.getClass().getInterfaces(), handler);
    }
}
public class SuperMan implements Human{
    @Override
    public String getBelief() {
        return "fly";
    }

    @Override
    public void eat(String food) {
        System.out.println("我喜欢吃"+food);
    }
}
public class Test {
    public static void main(String[] args) {
        SuperMan superMan=new SuperMan();
        Human human=(Human) ProxyFactory.getProxyInstance(superMan);
        String belief=human.getBelief();
        System.out.println(belief);
        human.eat("麻辣烫");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值