1.静态代理

public interface Person{
    public void buy();
}
public class Son implements Person{
    @Override
    public void buy(){
        System.out.println("我去买辣条");
    }
}
public class StaticProxy implements Person{

    private Person person;

    public StaticProxy(Person person){
        this.person = person;
    }


    @Override
    public void buy(){
        System.out.println("小明:你要去商店吗?");
        person.buy();
        System.out.println("小花:帮我也买一袋!");
    }

}
public class Demo{

    public static void main(String[] args){
        Person son = new Son();
        StaticProxy staticProxy = new StaticProxy(son);

        staticProxy.buy();
    }

}

 

2.动态代理(JDK)

public interface Person{
    public void buy();
}
public class Son implements Person{
    @Override
    public void buy(){
        System.out.println("我去买辣条");
    }
}
public class Dynamic implements InvocationHandler{
    private Object object;
    
    public Dynamic(Object object){
        this.object = object;
    }


    @Override
    public Object invoke(Object proxy,Method method ,Object[] objects) throws Throwable{
        System.out.println("小明:你要去商店吗?");
        Object invoke = method.invoke(object,objects);
        System.out.println("小花:帮我也买一袋");
        return invoke;
    }
}
public class DemoP{

    public static void main(String[] args){
        Person son = new Son();
        Dynamic dynamic = new Danamic(son);
        Person sonProxy = (Person)Proxy.newProxyInstance(
                                son.getClass().getClassLoader(),
                                son.getClass().getInterfaces(),
                                dynamic
                           );
        sonProxy.buy();
    }
}

 

3.动态代理(CGLIB)

public class Son{
    public void buy(){
        System.out.println("我去买辣条!!!");
    }
}
public class Cglib implements MethodInterceptor{

    @Override
    public Object intercept(Object object,Method method,
                            Object[] objects,MethodProxy methodProxy){
        System.out.println("小明:你要去商店吗?");
        Object proxy = methodProxy.invokeSuper(object,objects);
        System.out.println("小花:帮我也买一袋!");
        return proxy;
    }
}
public class Demo{

    public static void main(String[] args){

        Cglib cglib = new Cglib();

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Son.class);
        enhancer.setCallback(cglib);

        Son sonProxy = (Son)enhancer.create();
        sonProxy.buy();
    }

}

 

最后修改于 2020-08-20 10:48:56
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付
上一篇