• 设计模式复习 之 代理模式


    1. Java实现

    interface NetWork
    {
    public abstract void browser();
    }
    class Real implements NetWork
    {
    @Override
    public void browser() {
    // TODO Auto-generated method stub
    System.out.println("浏览信息");
    }
    }
    public class designpattern_proxy implements NetWork{
    private NetWork newwork;
    designpattern_proxy(NetWork network)
    {
    this.newwork = network;
    }
    @Override
    public void browser() {
    // TODO Auto-generated method stub
    this.newwork.browser();
    }
    public static void main(String [] args)
    {
    new designpattern_proxy(new Real()).browser();
    }
    }

      2. 动态代理

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

    interface NetWork
    {
    public abstract void browser();
    }
    class Real implements NetWork
    {
    @Override
    public void browser() {
    // TODO Auto-generated method stub
    System.out.println("浏览信息");
    }
    }
    //继承自InvocationHandler Override它的invoke()方法
      public class designpattern_dynmicproxy implements InvocationHandler{
    private Object sub;
    public designpattern_dynmicproxy(){}
    public designpattern_dynmicproxy(Object obj)
    {
    this.sub = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable {
    // TODO Auto-generated method stub
    System.out.println("before calling " + method);
    method.invoke(sub, args);
    System.out.println(
    "after calling " + method);
    return null;
    }


    public static void main(String [] args)
    {
    Real r
    = new Real();
    InvocationHandler ds
    = new designpattern_dynmicproxy(r);
    Class cls
    = r.getClass();
    NetWork nw
    = (NetWork)Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(),ds);
    nw.browser();
    }


    }

      

  • 相关阅读:
    一些开源工具软件
    被伤过的心还可以爱谁
    C函数检测CPU架构为LittleEndian或BigEndian
    C#打印(接录)
    C#Lambda表达式参考
    C#反射 创建对象,调用方法
    datagridview cell 验证事件
    我多想抱着你哭
    C#获取属性
    STM32的位操作的方法
  • 原文地址:https://www.cnblogs.com/hitwtx/p/2157189.html
Copyright © 2020-2023  润新知