zoukankan      html  css  js  c++  java
  • 设计模式复习 之 代理模式

    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();
    }


    }

      

  • 相关阅读:
    Revolving Digits[EXKMP]
    字符加密Cipher(bzoj 1031)
    Hotaru's problem
    1089 最长回文子串 V2(Manacher算法)
    3172: [Tjoi2013]单词
    3689: 异或之
    3942: [Usaco2015 Feb]Censoring [KMP]
    2795: [Poi2012]A Horrible Poem
    GT考试(bzoj 1009)
    NOIP2016提高组解题报告
  • 原文地址:https://www.cnblogs.com/hitwtx/p/2157189.html
Copyright © 2011-2022 走看看