您的位置:首页 > 职场人生

黑马程序员 JDBC_通过代理模式来保持用户关闭连接的习惯,代理设计模式(李勇老师)

2014-01-03 14:34 267 查看
很多框架都是采用这种代理的这种形式,但是以下代码可能不严谨,对于学习框架还是很有用的。



数据源包下的mycollection:

public class MyConnection implements Connection {
private Connection realConnection;
private MyDataSource2 dataSource;
private int maxUseCount = 5;
private int currentUserCount = 0;

MyConnection(Connection connection, MyDataSource2 dataSource) {
this.realConnection = connection;
this.dataSource = dataSource;
}

public void clearWarnings() throws SQLException {
this.realConnection.clearWarnings();
}

public void close() throws SQLException {
this.currentUserCount++;
if (this.currentUserCount < this.maxUseCount)
this.dataSource.connectionsPool.addLast(this);
else {
this.realConnection.close();
this.dataSource.currentCount--;
}
}

public void commit() throws SQLException {
this.realConnection.commit();
}

public Statement createStatement() throws SQLException {
return this.realConnection.createStatement();
}

public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException {
// TODO Auto-generated method stub
return null;
}

public Statement createStatement(int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
}

public boolean getAutoCommit() throws SQLException {
// TODO Auto-generated method stub
return false;
}

public String getCatalog() throws SQLException {
// TODO Auto-generated method stub
return null;
}

public int getHoldability() throws SQLException {
// TODO Auto-generated method stub
return 0;
}

public DatabaseMetaData getMetaData() throws SQLException {
// TODO Auto-generated method stub
return null;
}

public int getTransactionIsolation() throws SQLException {
// TODO Auto-generated method stub
return 0;
}

public Map<String, Class<?>> getTypeMap() throws SQLException {
// TODO Auto-generated method stub
return null;
}

public SQLWarning getWarnings() throws SQLException {
// TODO Auto-generated method stub
return null;
}

public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
return false;
}

public boolean isReadOnly() throws SQLException {
// TODO Auto-generated method stub
return false;
}

public String nativeSQL(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
}

public CallableStatement prepareCall(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
}

public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
// TODO Auto-generated method stub
return null;
}

public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
}

public PreparedStatement prepareStatement(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
}

public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
throws SQLException {
// TODO Auto-generated method stub
return null;
}

public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
throws SQLException {
// TODO Auto-generated method stub
return null;
}

public PreparedStatement prepareStatement(String sql, String[] columnNames)
throws SQLException {
// TODO Auto-generated method stub
return null;
}

public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
// TODO Auto-generated method stub
return null;
}

public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
}

public void releaseSavepoint(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub

}

public void rollback() throws SQLException {
// TODO Auto-generated method stub

}

public void rollback(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub

}

public void setAutoCommit(boolean autoCommit) throws SQLException {
// TODO Auto-generated method stub

}

public void setCatalog(String catalog) throws SQLException {
// TODO Auto-generated method stub

}

public void setHoldability(int holdability) throws SQLException {
// TODO Auto-generated method stub

}

public void setReadOnly(boolean readOnly) throws SQLException {
// TODO Auto-generated method stub

}

public Savepoint setSavepoint() throws SQLException {
// TODO Auto-generated method stub
return null;
}

public Savepoint setSavepoint(String name) throws SQLException {
// TODO Auto-generated method stub
return null;
}

public void setTransactionIsolation(int level) throws SQLException {
// TODO Auto-generated method stub

}

public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
// TODO Auto-generated method stub

}

@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}

@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}

@Override
public Clob createClob() throws SQLException {
// TODO Auto-generated method stub
return null;
}

@Override
public Blob createBlob() throws SQLException {
// TODO Auto-generated method stub
return null;
}

@Override
public NClob createNClob() throws SQLException {
// TODO Auto-generated method stub
return null;
}

@Override
public SQLXML createSQLXML() throws SQLException {
// TODO Auto-generated method stub
return null;
}

@Override
public boolean isValid(int timeout) throws SQLException {
// TODO Auto-generated method stub
return false;
}

@Override
public void setClientInfo(String name, String value)
throws SQLClientInfoException {
// TODO Auto-generated method stub

}

@Override
public void setClientInfo(Properties properties)
throws SQLClientInfoException {
// TODO Auto-generated method stub

}

@Override
public String getClientInfo(String name) throws SQLException {
// TODO Auto-generated method stub
return null;
}

@Override
public Properties getClientInfo() throws SQLException {
// TODO Auto-generated method stub
return null;
}

@Override
public Array createArrayOf(String typeName, Object[] elements)
throws SQLException {
// TODO Auto-generated method stub
return null;
}

@Override
public Struct createStruct(String typeName, Object[] attributes)
throws SQLException {
// TODO Auto-generated method stub
return null;
}

@Override
public void setSchema(String schema) throws SQLException {
// TODO Auto-generated method stub

}

@Override
public String getSchema() throws SQLException {
// TODO Auto-generated method stub
return null;
}

@Override
public void abort(Executor executor) throws SQLException {
// TODO Auto-generated method stub

}

@Override
public void setNetworkTimeout(Executor executor, int milliseconds)
throws SQLException {
// TODO Auto-generated method stub

}

@Override
public int getNetworkTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}

}


数据源代码:真正开发时,是不需要自己写的。

public class MyDataSource2 implements DataSource {
private static String url = "jdbc:mysql://localhost:3306/jdbc";
private static String user = "root";
private static String password = "root";

private static int initCount = 1;
private static int maxCount = 1;
int currentCount = 0;

LinkedList<Connection> connectionsPool = new LinkedList<Connection>();// 针对接口编程,connection是接口

public MyDataSource2() {
try {
for (int i = 0; i < initCount; i++) {
this.connectionsPool.addLast(this.createConnection());
this.currentCount++;
}
} catch (SQLException e) {
throw new ExceptionInInitializerError(e);
}
}

public Connection getConnection() throws SQLException {
synchronized (connectionsPool) {
if (this.connectionsPool.size() > 0)
return this.connectionsPool.removeFirst();

if (this.currentCount < maxCount) {
this.currentCount++;
return this.createConnection();
}

throw new SQLException("已没有链接");
}
}

public void free(Connection conn) {
this.connectionsPool.addLast(conn);
}

private Connection createConnection() throws SQLException {
Connection realConn = DriverManager.getConnection(url, user, password);
MyConnection myConnection = new MyConnection(realConn, this);
return myConnection;

}

public Connection getConnection(String username, String password)
throws SQLException {
// TODO Auto-generated method stub
return null;
}

public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
}

public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}

public void setLogWriter(PrintWriter out) throws SQLException {
// TODO Auto-generated method stub

}

public void setLoginTimeout(int seconds) throws SQLException {
// TODO Auto-generated method stub

}

@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
}

@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}

@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
}


连接数据库的工具类:调用的依然是关闭的方法close,但是被拦截下来啦,执行的结果不一样,不是关闭数据库的连接

public final class JdbcUtils {

private static MyDataSource2 myDataSource = null;

private JdbcUtils() {
}

static {
try {
Class.forName("com.mysql.jdbc.Driver");
myDataSource = new MyDataSource2();
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}

public static DataSource getDataSource() {
return myDataSource;
}

public static Connection getConnection() throws SQLException {
// return DriverManager.getConnection(url, user, password);
return myDataSource.getConnection();
}

public static void free(ResultSet rs, Statement st, Connection conn) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null)
try {
conn.close();
// myDataSource.free(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}


测试代码:

public static void main(String[] args) throws Exception {

for (int i = 0; i < 10; i++) {

Connection conn = JdbcUtils.getConnection();

System.out.println(conn);

JdbcUtils.free(null, null, conn);

}

}

自己建立一个connection,实现connection接口,覆盖close方法,一调用close方法,不是关闭连接而是把连接加入到连接池,让别的开发人员使用起来和调用以前的close方法一样

结果:

cn.itcast.jdbc.datasource.MyConnection@def14f

cn.itcast.jdbc.datasource.MyConnection@def14f

cn.itcast.jdbc.datasource.MyConnection@def14f

cn.itcast.jdbc.datasource.MyConnection@def14f

cn.itcast.jdbc.datasource.MyConnection@def14f

cn.itcast.jdbc.datasource.MyConnection@836727

cn.itcast.jdbc.datasource.MyConnection@836727

cn.itcast.jdbc.datasource.MyConnection@836727

cn.itcast.jdbc.datasource.MyConnection@836727

cn.itcast.jdbc.datasource.MyConnection@836727
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: