8.代理模式

1.组合模式的静态代理

public class NormalClassProxy {
    private Apple apple;
    public NormalClassProxy(Apple apple){
        this.apple = apple;
    }

    void eat(){
        System.out.println("before eat");
        apple.eat();
    }

    public static void main(String[] args) {
        new NormalClassProxy(new Apple()).eat();
    }
}

class Apple{
    void eat(){
        System.out.println("eat apple");
    }
}

2.接口模式的静态代理

public class NormalInterfaceProxy implements Fruit{
    private Fruit target;
    public NormalInterfaceProxy(Fruit target){
        this.target = target;
    }

    public void eat() {
        System.out.println("before eat");
        target.eat();
    }

    public static void main(String[] args) {
        new NormalInterfaceProxy(new Orange()).eat();
    }
}

interface Fruit{
    void eat();
}
class Orange implements Fruit{

    public void eat() {
        System.out.println("eat Orange");
    }
}

3.JDK模式的动态代理

//中介类
public class JdkProxy implements InvocationHandler {

    private Object target;
    public JdkProxy(Object target){
        this.target = target;
    }

    public static void main(String[] args) {
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

        JdkProxy jdkProxy = new JdkProxy(new Printer());
        //代理类
        Inter inter = (Inter)Proxy.newProxyInstance(JdkProxy.class.getClassLoader(),new Class[]{Inter.class},jdkProxy);
        inter.print();

    }


    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before");
        method.invoke(target,args);
        System.out.println("after");
        return null;
    }
}

interface Inter{
    void print();
}
//目标类
class Printer implements Inter{
    public void print(){
        System.out.println("Printer print");
    }
}

4.cglib模式的动态代理

import java.lang.reflect.Method;

public class Printer {

    public  void print(){
        System.out.println("Printer print");
        print2();
    }

    public  void print2(){
        System.out.println("Printer print2");
    }

    static class Logger implements MethodInterceptor{

        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println("before");
            methodProxy.invokeSuper(o,objects);
            System.out.println("after");
            return null;
        }

        public Object getInstance(Class clazz){
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(clazz);
            enhancer.setCallback(this);
            return enhancer.create();
        }
    }

    public static void main(String[] args) {
        Printer printer = (Printer)new Printer.Logger().getInstance(Printer.class);
        printer.print();
    }
}

  

上一篇:SQL Server提高并发查询效率


下一篇:Nutrispoter: Eat like a sporter