Proxy模式以及java动态代理实现
一. Proxy模式定义:
为其他对象提供一种代理以控制这个对象的访问.
二.模式解说
Proxy代理模式是一种结构型设计模式,主要解决的问题是:在直接访问对象时带来的问题,比如说:要访问的对象在远程的机器上.
在面向对象系统中,有些对象由于某些原因(比如对象创建开销很大,或者某些操作需要安全控制,或者需要进程外的访问),
直接访问会给使用者或者系统结构带来很多麻烦,我们可以在访问此对象时加上一个对此对象的访问层,这个访问层也叫代理。
Proxy模式是最常见的模式,在我们生活中处处可见,比如现在有个什么哥,特别的火,但是性别一般人看不出来,你去问"他",人家是
大腕,不和你直接对话,只有经纪人出面,这个经纪人就可以看成他的代理.
三.结构图
传统的结构图如下:
java动态代理结构图如下:
四.实现:
public interface Person {
public void ownSex();
public String isBoolean(String str);
}
public class SpringBrother implements Person {
public void ownSex() {
System.out.println("Female!");
}
public String isBoolean(String str) {
return "yes!";
}
}
public class MyInvocationHandler implements InvocationHandler {
private Object proxied = null; //被代理的对象.
public MyInvocationHandler(Object proxied){
this.proxied = proxied;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("---------- proxy: ----------\n" + proxy.getClass()
+ "\nmethod: " + method + "\nargs: " + args);
Object oo = method.invoke(proxied, args);// 访问底层方法,这里是main方法中的ownSex或者isBoolean,返回返回值
if(args!=null && args.length!=0){
for(Object o : args){
System.out.println(o);
}
}
if(!(oo==null)){
System.out.println(oo);
}
return null;
}
public static void main(String[] args) {
Person person = (Person)Proxy.newProxyInstance(MyInvocationHandler.class.getClassLoader(),
new Class[]{Person.class}, new MyInvocationHandler(new SpringBrother()));
person.ownSex();
person.isBoolean("is Female!
相关文档:
Java NIO API详解
在JDK
1.4以前,Java的IO操作集中在java.io这个包中,是基于流的阻塞(blocking)API。对于大多数应用来说,这样的API使用很方
便,然而,一些对性能要求较高的应用,尤其是服务端应用,往往需要一个更为有效的方式来处理IO。从JDK 1.4起,NIO
API作为一个基于缓冲区,并能提供非阻塞(non-blo ......
一:准备 www.savarese.org download
1. rocksaw-1.0.0-src.tar.gz
2. vserv-tcpip-0.9.2-src.tar.gz
二:编译源文件得到jar包 使用Ant
1. build vserv-tcpip-0.9.2-src
在vserv-tcpip-0.9.2目录下面建一个tests目录,然后在cmd窗口下进入 ......
http://blog.csdn.net/ycyangcai/archive/2009/06/21/4285997.aspx
1.声明一个map: Map map = new HashMap();
2.向map中放值,注意:map是key-value的形式存放的.如:
map.put("sa","dd");
3.从map中取值:String str = map.get("sa").toString();结果是:str = "dd";
4.遍历一个map,从 ......
Caused by: java.sql.SQLException: ORA-00918: column ambiguously defined
Caused by: com.ibatis.common.jdbc.exception.NestedSQLException:
--- The error occurred in com/ibatis/jpetstore/persistence/sqlmapdao/sql/Item.xml.
--- The error occurred while applying a parameter map.&nbs ......
String s = new String("abc");
String s1 = "abc";
String s2 = new String("abc");
System.out.println(s == s1);
System.out.println(s == s2);
S ......