posts - 66,  comments - 11,  trackbacks - 0
    Decorator模式:简单来讲,就是通过一个Decorator对原有对象进行封装,同事实现与原有对象相同的接口,从而得到一个基于原有对象的,对既有接口的增强型实现。
    首先引入一个ConnectionDecorator类:
   
public class ConnectionDecorator implements Connection{
      Connection dbconn;
      
public ConnectionDecorator(Connnection conn){
        
this.dbconn = conn;//实际从数据库获得的Connection引用
      }
      
public void close()throws SQLException{
        
this.dbconn.close();
      }
      
public void commit()throws SQLException{
        
this.dbconn.commit();//调用实际连接的commit方法
      }
      
    }
    ConnectionDecorator类实际上是对传入的数据库连接加上了一个外壳,它实现了java.sql.Connection接口,不过本身并没有实现任何实际内容,只是简单的把方法的实现委托给运行期实际获得的Connection实例,而从外部看,ConnectionDecorator与普通的Connection实例没有什么区别。
   
public class PooledConnection extends ConnectionDecorator implements Connection{
      
private ConnectionPool connPool;
      
public PooledConnection(ConnectionPool pool,Connection conn){
        
super(conn);
        connPool 
= pool;
      }
      
//覆盖close方法,将数据库连接返回连接池中,而不是直接关闭连接
      public void close()throws SQLException{
        connPool.releaseConnection(
this.dbconn);
      }
}

动态代理:
  
public class ConnectionHandler implements InvocationHandler{
      Connection dbconn;
      ConnectionPool pool;

      
public ConnectionHandler(ConnectionPool connPool){
        
this.pool = connPool;
      }
      
//将动态代理绑定到指定Connection
      public Connection bind(Connection conn){
        
this.dbconn = conn;
        Connection proxyConn 
= (Connection)Proxy.newProxyInstance(conn.getClass().getClassLoader(),conn.getClass().getInterfaces(),this);
        
return proxyConn;
      }
      
//方法调用拦截器
      public Object invoke(Object proxy,Method method,Object[] args)throws Throwable{
        Object obj 
=null;
        
if("close".equals(method.getName())){
          pool.releaseConnection(dbconn);
        }
else{
          obj 
= method.invoke(dbconn,args);
        }
        
return obj;
      }
    }
    ConnectionHandler connHandler 
= new ConnectionHandler(this);
    
return connHandler.bind(conn);
可以看到,基于Dynamic Proxy模式的实现相对Decorator更加简洁明了。

posted on 2009-10-08 10:02 王永庆 阅读(188) 评论(0)  编辑  收藏 所属分类: HIBERNATE

只有注册用户登录后才能发表评论。


网站导航:
 
<2009年10月>
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

常用链接

留言簿(1)

随笔分类

随笔档案

关注blogs

搜索

  •  

最新评论

阅读排行榜

评论排行榜