通知 网站从因情语写改为晴雨,这个网站的模板也从calmlog_ex改为 whimurmur

结构型模式-代理模式

580人浏览 / 0人评论 / | 作者:因情语写  | 分类: 设计模式与算法  | 标签: 设计模式与算法

作者:因情语写

链接:https://www.qingyu.blue/article/449

声明:请尊重原作者的劳动,如需转载请注明出处


  代理模式和装饰器模式比较相似,都是对原有对象进行额外的操作,不同的是装饰器是对原有对象的修饰,而代理模式是接手原对象的功能,并决定原功能的执行情况

  先来看静态代理的例子,用户管理

package constructional.pattern.proxy.staticproxy;
/***
 * 用户控制接口
 * @author Administrator
 *
 */
public interface UserManager {

    public void addUser(String userId,String userName);
    public void modifyUser(String userId,String userName);
    public void delUser(String userId);
    public String findUser(String userId);
}
package constructional.pattern.proxy.staticproxy;

/****
 * 用户管理真正的实现类
 * @author Administrator
 *
 */
public class UserManagerImpl implements UserManager {

    /*****
     * 添加用户
     */
    public void addUser(String userId, String userName) {
            System.out.println("正在添加用户,用户为:"+userId+userName+"……");
    }
    /*****
     * 删除用户
     */
    public void delUser(String userId) {
        System.out.println("delUser,userId="+userId);
    }
    /***
     * 查找用户
     */
    public String findUser(String userId) {
        System.out.println("findUser,userId="+userId);
        return userId;
    }

    public void modifyUser(String userId, String userName) {
        System.out.println("modifyUser,userId="+userId);
    }
}
package constructional.pattern.proxy.staticproxy;

/***
 * 代理类,提供用户实现类的访问控制
 * @author Administrator
 *
 */
public class Proxy implements UserManager{
    private UserManager userManager;
    public Proxy(UserManagerImpl ul)
    {
        userManager=ul;
    }
    public void addUser(String userId, String userName) {
        System.out.println("正在进行添加用户前的准备工作,用户id为:"+userId+"……");
        try {
            userManager.addUser(userId, userName);
            System.out.println("成功添加用户"+userId+",正在进行确认处理……");
        } catch (Exception e) {
            System.out.println("添加,userId="+userId+"失败!");
        }
        
        
    }

    public void delUser(String userId) {
        // TODO Auto-generated method stub
        
    }

    public String findUser(String userId) {
        // TODO Auto-generated method stub
        return null;
    }

    public void modifyUser(String userId, String userName) {
        // TODO Auto-generated method stub
    }
}

  测试代码

package constructional.pattern.proxy.staticproxy;

/****
 * 客户端
 * @author Administrator
 *
 */
public class Client {

        public static void main(String []args)
        {
            UserManager userManager=new Proxy( new UserManagerImpl());
            userManager.addUser("0001", "张三");
        }
}

  运行结果

  看完了静态代理,再来看看动态代理,正常的动态代理

package constructional.pattern.proxy.dynamicproxy;

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

public class LoginHandler2 implements InvocationHandler {


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

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        System.out.println("登录成功");
        try {
            method.invoke(target, null);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
package constructional.pattern.proxy.dynamicproxy;

public class User implements UserMgr{

    @Override
    public void addUser() {
        System.out.println("添加用户");
        
    }
}
package constructional.pattern.proxy.dynamicproxy;

public interface UserMgr {

    public void addUser();
}

  测试代码

package constructional.pattern.proxy.dynamicproxy;

import java.lang.reflect.Proxy;

public class JdkTest2 {
    public static void main(String args[]){
        User u = new User();
        LoginHandler2 l = new LoginHandler2(u);
        ClassLoader c = ClassLoader.getSystemClassLoader();
        try {
            UserMgr ur = (UserMgr)Proxy.newProxyInstance(c,new Class[]{UserMgr.class}, l);
            ur.addUser();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

  运行结果

  下面是手动编译代理类的代码

package constructional.pattern.proxy.dynamicproxy;

import java.lang.reflect.Method;

public interface InvocationHandler {

    public void invoke(Object o,Method m);
}
package constructional.pattern.proxy.dynamicproxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class LoginHandler implements InvocationHandler{

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

    @Override
    public void invoke(Object o, Method m) {
        System.out.println("登录成功");
        try {
            m.invoke(target, null);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
package constructional.pattern.proxy.dynamicproxy;

public interface UserMgr {

    public void addUser();
}
package constructional.pattern.proxy.dynamicproxy;

public class User implements UserMgr{

    @Override
    public void addUser() {
        System.out.println("添加用户");
        
    }
}
package constructional.pattern.proxy.dynamicproxy;

import java.io.FileWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Random;

import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
public class Proxy {

    public static Object getProxyInstance(Class inface,InvocationHandler h) throws Exception{
        String rt ="\r\t";
        byte[] bytes = new byte[1];
        bytes[0] = 1;
        String className = "P" + Math.abs(new Random().nextLong());
        String methodStr = "";
//        for(Method m:inface.getMethods()){
//            methodStr+="    @Override" + rt+
//                        "    public void " + m.getName() + "(){" + rt +
//                        "            long startTime = System.currentTimeMillis();"+ rt +
//                        "            System.out.println(\"startTime:\"+startTime);"+ rt +
//                        "            t." + m.getName() + "()" + ";"+ rt +
//                        "            long endTime = System.currentTimeMillis();"+ rt +
//                        "            System.out.println(\"Time:\"+(endTime-startTime));"+ rt +
//
//                        "     }" + rt;
//
//        }
        for(Method m : inface.getMethods()) {
            methodStr += "@Override" + rt + 
                         "public void " + m.getName() + "() {" + rt +
                         "    try {" + rt +
                         "    Method md = " + inface.getName() + ".class.getMethod(\"" + m.getName() + "\");" + rt +
                         "    h.invoke(this, md);" + rt +
                         "    }catch(Exception e) {e.printStackTrace();}" + rt +
                        
                         "}";
        }

        
        
        String str = 
        
        "package constructional.pattern.proxy.dynamicproxy;"+ rt +
        "import java.lang.reflect.Method;" + rt +
        "public class " + className + "Proxy implements " +inface.getName()+ "{"+ rt +

        "   constructional.pattern.proxy.dynamicproxy.InvocationHandler h;" + rt +
            
            
        "    public " + className + "Proxy(InvocationHandler h) {"+ rt +
        "        super();"+ rt +
        "        this.h = h;"+ rt +
        "}"+ rt +

            methodStr+

        "}";
        String fileName =System.getProperty("user.dir")+"/src/constructional/pattern/proxy/dynamicproxy/" + className + "Proxy.java";
        FileWriter fw = new FileWriter(fileName);
        fw.write(str);
        fw.flush();
        fw.close();
        //compile
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileMgr = compiler.getStandardFileManager(null, null, null);
        Iterable units = fileMgr.getJavaFileObjects(fileName);
        CompilationTask t = compiler.getTask(null, fileMgr, null, null, null, units);
        t.call();
        fileMgr.close();
        
        //load into memory and create an instance
        URL[] urls = new URL[]{(new URL("file:/"+System.getProperty("user.dir")+"/src/"))};
        URLClassLoader ul = new URLClassLoader(urls);
        Class c = ul.loadClass("constructional.pattern.proxy.dynamicproxy." + className +"Proxy");
        System.out.println(c);
        Constructor ctr = c.getConstructor(InvocationHandler.class);
        Object m = (Object)ctr.newInstance(h);
        return m;
    }
}

 

  测试类

package constructional.pattern.proxy.dynamicproxy;

public class Test2 {

    public static void main(String args[]){
        User u = new User();
        LoginHandler l = new LoginHandler(u);
        try {
            UserMgr ur = (UserMgr)Proxy.getProxyInstance(UserMgr.class, l);
            ur.addUser();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
}

 

  运行结果


自己写的文章声明标题示例:


点赞(0) 打赏

全部评论

还没有评论!