JAVA静态代理和动态代理

动态代理

interface People{
    void dance();

    String eat(String food);

    void run();
}

//创建被代理类
class ManPeople implements People{

    @Override
    public void dance() {
        System.out.println("男人调街舞");
    }

    @Override
    public String eat(String food) {
        return "男人吃:"+food;
    }

    @Override
    public void run() {
        System.out.println("男人跑5000米");
    }
}

class WomanPeople implements  People{

    @Override
    public void dance() {
        System.out.println("女人调中国舞");
    }

    @Override
    public String eat(String food) {
        return "女人吃:"+food;
    }

    @Override
    public void run() {
        System.out.println("女人跑100米");
    }
}
//代理工厂
class ProxyFactory{
    //生产代理类对象
    public static Object getProxyInstance(Object obj){ //obj被代理类对象
        MyInvocationHandler handler = new MyInvocationHandler();
        handler.bind(obj);
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),handler);
    }
}

class MyInvocationHandler implements InvocationHandler{
    private Object obj;

    public void bind(Object obj){
        this.obj = obj;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //代理类对象调用的方法- obj指向被代理类对象 , 所以这里调用的是被代理类方法
        Object returnValue = method.invoke(obj,args);
        return returnValue;
    }
}

public class ProxyTest {
    public static void main(String[] args) {
        //先创建代理类对象
        ManPeople manPeople = new ManPeople();
        People proxyInstance = (People) ProxyFactory.getProxyInstance(manPeople);
        proxyInstance.dance();
        proxyInstance.run();


        WomanPeople womanPeople = new WomanPeople();
        People proxyInstancew = (People) ProxyFactory.getProxyInstance(womanPeople);
        proxyInstancew.dance();
        proxyInstancew.run();
    }
}

静态代理

interface ClothFactory{
    void productCloth();
}

//代理类
class ClothFactoryProxy implements ClothFactory{
    private ClothFactory factory;

    public ClothFactoryProxy(ClothFactory factory){
        this.factory = factory;
    }
    @Override
    public void productCloth() {
        factory.productCloth();
    }
}

//被代理类
class NickClothFactory implements ClothFactory{

    @Override
    public void productCloth() {
        System.out.println("被代理类执行了");
    }
}
public class ProxyStatic {
    public static void main(String[] args) {
        NickClothFactory nickClothFactory = new NickClothFactory();
        ClothFactoryProxy clothFactoryProxy = new ClothFactoryProxy(nickClothFactory);
        clothFactoryProxy.productCloth();
    }
}

 

posted @ 2022-06-11 18:43  FinnYY  阅读(21)  评论(0编辑  收藏  举报