首先引入一個ConnectionDecorator類:
public class ConnectionDecorator implements Connection{
Connection dbconn;
public ConnectionDecorator(Connnection conn){
this.dbconn = conn;//實際從數(shù)據(jù)庫獲得的Connection引用
}
public void close()throws SQLException{
this.dbconn.close();
}
public void commit()throws SQLException{
this.dbconn.commit();//調(diào)用實際連接的commit方法
}

}
ConnectionDecorator類實際上是對傳入的數(shù)據(jù)庫連接加上了一個外殼,它實現(xiàn)了java.sql.Connection接口,不過本身并沒有實現(xiàn)任何實際內(nèi)容,只是簡單的把方法的實現(xiàn)委托給運行期實際獲得的Connection實例,而從外部看,ConnectionDecorator與普通的Connection實例沒有什么區(qū)別。Connection dbconn;
public ConnectionDecorator(Connnection conn){
this.dbconn = conn;//實際從數(shù)據(jù)庫獲得的Connection引用
}
public void close()throws SQLException{
this.dbconn.close();
}
public void commit()throws SQLException{
this.dbconn.commit();//調(diào)用實際連接的commit方法
}

}
public class PooledConnection extends ConnectionDecorator implements Connection{
private ConnectionPool connPool;
public PooledConnection(ConnectionPool pool,Connection conn){
super(conn);
connPool = pool;
}
//覆蓋close方法,將數(shù)據(jù)庫連接返回連接池中,而不是直接關閉連接
public void close()throws SQLException{
connPool.releaseConnection(this.dbconn);
}
}
private ConnectionPool connPool;
public PooledConnection(ConnectionPool pool,Connection conn){
super(conn);
connPool = pool;
}
//覆蓋close方法,將數(shù)據(jù)庫連接返回連接池中,而不是直接關閉連接
public void close()throws SQLException{
connPool.releaseConnection(this.dbconn);
}
}
動態(tài)代理:
public class ConnectionHandler implements InvocationHandler{
Connection dbconn;
ConnectionPool pool;
public ConnectionHandler(ConnectionPool connPool){
this.pool = connPool;
}
//將動態(tài)代理綁定到指定Connection
public Connection bind(Connection conn){
this.dbconn = conn;
Connection proxyConn = (Connection)Proxy.newProxyInstance(conn.getClass().getClassLoader(),conn.getClass().getInterfaces(),this);
return proxyConn;
}
//方法調(diào)用攔截器
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模式的實現(xiàn)相對Decorator更加簡潔明了。Connection dbconn;
ConnectionPool pool;
public ConnectionHandler(ConnectionPool connPool){
this.pool = connPool;
}
//將動態(tài)代理綁定到指定Connection
public Connection bind(Connection conn){
this.dbconn = conn;
Connection proxyConn = (Connection)Proxy.newProxyInstance(conn.getClass().getClassLoader(),conn.getClass().getInterfaces(),this);
return proxyConn;
}
//方法調(diào)用攔截器
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);