代理模式(Proxy) Java
2016-06-23 18:22
591 查看
定义:
代理模式: 为其他对象提供一种代理以控制对这个对象的访问。使用场合:
远程代理,一个对象在不同的地址空间提供局部代表。这样可以隐藏一个对象存在于不同地址空间的事实。
虚拟代理,创建对象开销很大,通过代理模式来存放实例化很长时间的真实对象。
安全代理,可以控制真实对象的访问权限。
类图:
代码:
package ding.study.designpatterns.proxy;/**
* 请求接口
* @author daniel
* @email 576699909@qq.com
* @time 2016-5-19 上午10:34:51
*/
public interface Subject {
/**
* 发出请求
* @author daniel
* @time 2016-5-19 上午10:34:58
*/
public void request();
}
package ding.study.designpatterns.proxy;
/**
* 请求实现类
* @author daniel
* @email 576699909@qq.com
* @time 2016-5-19 上午10:42:42
*/
public class SubjectImpl implements Subject {
@Override
public void request() {
System.out.println("发出请求");
}
}
package ding.study.designpatterns.proxy;
/**
* 代理类
*
* @author daniel
* @email 576699909@qq.com
* @time 2016-5-19 上午10:42:33
*/
public class Proxy implements Subject {
private Subject subject;
@Override
public void request() {
if (subject == null) {
subject = new SubjectImpl();
}
subject.request();
}
}
package ding.study.designpatterns.proxy;
import java.util.ArrayList;
import java.util.List;
/**
* 代理模式:为其他对象提供一种代理以控制对这个对象的访问。
*
* 使用场合:
*
* 远程代理,一个对象在不同的地址空间提供局部代表。这样可以隐藏一个对象存在于不同地址空间的事实。
*
* 虚拟代理,创建对象开销很大,通过代理模式来存放实例化很长时间的真实对象。
*
* 安全代理,可以控制真实对象的访问权限。
*
* @author daniel
* @email 576699909@qq.com
* @time 2016-5-19 上午10:44:26
*/
public class Zmain {
/**
* @author daniel
* @time 2016-5-19 上午10:43:07
* @param args
*/
public static void main(String[] args) {
Proxy proxy = new Proxy();
proxy.request();
/* Wan w=new Wan();
WanInvocationImpl impl = new WanInvocationImpl(w);
Wan wan = (Wan)Proxy.newProxyInstance(Wan.class.getClassLoader(),new Class[] { Wan.class }, impl);
wan.run();
List list=(List)ProxyUtil.newProxyInstance(new ArrayList(), new MyAdvice());
list.add("aa");
list.add("bb");
System.out.println(list.size());
list.clear();
System.out.println(list.size());
WanImpl list=(WanImpl)ProxyUtil.newProxyInstance(new WanImpl(), new MyAdvice());
list.run();*/
}
}
源码:
https://github.com/dingsai88/StudyTest/tree/master/src/ding/study/designpatterns/proxy相关文章推荐
- PKAV 发现 Struts2 最新远程命令执行漏洞(S2-037)
- 2016.6.23笔记(2)-本地配置
- spring定时任务.线程池,自定义多线程配置
- Java中的byte[]/char[]/int/String数据类型转换
- JAVA 数组的初始化
- Struts2跳转结果页时没有css样式或图片的问题
- Java synchronized的使用
- 触发Full GC执行的情况
- RxJava 学习笔记(二)
- Spring声明式事务管理与配置介绍
- java.sql.SQLException: Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '=' 异常处理,及MySQL数据库编码设置
- 浅析Java中的final关键字
- java中将一个字符数组赋值给另一个,两者同时变化
- Spring MVC程序中怎么得到静态资源文件css,js,图片文件的路径问题
- JAVA实现DES加密实现详解
- javaweb中文件上传下载示例
- JS加密Java解密报rsa bad argument
- Spring MVC程序中得到静态资源文件css,js,图片
- java.io.File中的pathSeparator与separator的区别
- spring ioc 原理 spring aop原理