静态代理和静态代理

静态代理


public class Main{
    public static void main(String[] args) {
        NikeClothFactory nikeClothFactory =new NikeClothFactory();
        PorxyClothFactory porxyClothFactory = new PorxyClothFactory(nikeClothFactory);

        porxyClothFactory.produceCloth();
    }
}

interface ClothFactory {
    void produceCloth();
}

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

    public PorxyClothFactory() {
    }

    public PorxyClothFactory(ClothFactory factory) {
        this.factory = factory;
    }

    @Override
    public void produceCloth() {
        System.out.println("代理工厂开始工作...");

        factory.produceCloth();

        System.out.println("代理工厂完成工作.");
    }
}

// 被代理类
class NikeClothFactory implements ClothFactory{

    @Override
    public void produceCloth() {
        System.out.println("耐克工厂生产一批运动服...");
    }
}


动态代理

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

// 动态代理
public class ProxyTest {
    public static void main(String[] args) {
        // 例子1
        SuperMan superMan = new SuperMan();
        Human factory = (Human) ProxyFactory.getPoxyInctanc(superMan);
        String belief = factory.getBelief();
        factory.eat("四川麻辣烫");
        System.out.println(belief);


        // 例子2
        NikeClothFactory nikeClothFactory = new NikeClothFactory();
        ClothFactory factory1 = (ClothFactory) ProxyFactory.getPoxyInctanc(nikeClothFactory);
        factory1.produceCloth();

    }

}

interface Human {
    String getBelief();

    void eat(String food);
}

// 被代理类
class SuperMan implements Human {

    @Override
    public String getBelief() {
        return "I believe I can fly!";
    }

    @Override
    public void eat(String food) {
        System.out.println("我喜欢吃" + food);
    }
}

//问题一: 如何根据加载到内存中的被代理对象,动态的创建一个代理类及其对象
//问题二: 但通过代理类的对象调用方法时,如何动态的去调用被代理类中的同名方法
class ProxyFactory {
    // 调用此方法,返回一个代理对象
    public static Object getPoxyInctanc(Object obj) { // obj 被代理对象
        MyInvotaionHandler handler = new MyInvotaionHandler();
        handler.bind(obj);
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), handler);
    }
}

class MyInvotaionHandler implements InvocationHandler {
    private Object obj;// 需要使用被代理类的对象进行赋值

    public void bind(Object obj) {
        this.obj = obj;
    }

    // 当我们通过代理类的对象,调用a方法时,就会自动调用如下的方法,invoke()
    // 将被代理的方法要执行的a方法的功能就声明在invoke中
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object retunValue = method.invoke(obj, args);// method 即为被代理对象调用的方法
        return retunValue;
    }
}
posted @ 2022-03-26 11:04  诗酒  阅读(43)  评论(0编辑  收藏  举报