zoukankan      html  css  js  c++  java
  • 设计模式-代理模式

    定义: 为其他对象提供一种代理来控制这个对像的访问.

    IGamePlayer : 抽象的接口

    GamePlayer  : 实际的业务逻辑实现对象

    GameProxy : 代理对象.

    一 . 普通代理:

     代理类和被代理类继承同一个接口,代理类包含被代理类,用代理类执行时实际跑被代理类的方法。

    public class Proxy implements Subject {
    private RealSuject rSub;

    public Proxy(){
    rSub = new RealSuject();
    }
    public void request(String s) {
    /*此处新增RealSuject,不考虑多线程*/
    if(rSub == null){
    rSub = new RealSuject();
    }
    System.out.println("proxy function before call the real object");
    rSub.request(s);
    System.out.println("proxy function after call the real object");
    }

    }

    二.强制代理类

    类接口包含判断是否是代理的方法,被代理类只有指定了代理才能被访问,否则不能被访问。

    三.动态代理

    public class MyInvocationHandler implements InvocationHandler {

    private Object p ;
    public MyInvocationHandler(Object pro)
    {
    this.p = pro;
    }
    public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable {
    // TODO Auto-generated method stub
    return method.invoke(this.p, args);
    }

    }

    public class DynamicProxy<T> {
    public static <T>T newProxyInstance(ClassLoader cl,
    Class<?>[]interfaces,MyInvocationHandler mih){
    return (T)Proxy.newProxyInstance(cl, interfaces, mih);
    }
    }

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Subject s = new RealSuject();
    MyInvocationHandler mh = new MyInvocationHandler(s);
    Subject proxy = DynamicProxy.newProxyInstance(s.getClass().getClassLoader(),
    s.getClass().getInterfaces(), mh);
    proxy.request("hello");
    }

    使用的是java的代理基本方法。Proxy InvocationHandler

  • 相关阅读:
    LeetCode-Search a 2D Matrix
    Cocos2d-x 学习(1)—— 通过Cocos Studio创建第一个Demo
    SpringMVC经典系列-12基于SpringMVC的文件上传---【LinusZhu】
    poj 2126 Factoring a Polynomial 数学多项式分解
    [每天读书半小时] 2015-6-8 设计模式
    LeetCode_Path Sum II
    MySql截取DateTime字段的日期值
    Fiddler2 中文手册
    fiddler2抓包工具使用图文教程
    Fiddler2 抓取手机APP数据包
  • 原文地址:https://www.cnblogs.com/thinkqin/p/3819286.html
Copyright © 2011-2022 走看看