1.1.1 使用装饰者模式增强Connection中的close方法
为了简化编程,提供一个模板类(模板类原封不动的将接口中的所有方法都实现,但是都没有增强)。编写一个装饰类继承模板类。在装饰类中只需要增强某一个方法即可。
1.1.1.1 代码实现
1.1.1.2 测试代码
l 改写连接池
[AppleScript] 纯文本查看 复制代码
?
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | public class MyDataSource implements DataSource { / / 将一些连接存入到内存中,可以定义一个集合,用于存储连接对象。 private List < Connection > connList = new ArrayList < Connection > ( ) ; / / 在初始化的时候提供一些连接 public MyDataSource ( ) { / / 初始化连接: for ( int i = 1 ;i < = 3 ;i + + ) { / / 向集合中存入连接 : connList. add ( JDBCUtils.getConnection ( ) ) ; } } / / 从连接池中获得连接的方法 @Override public Connection getConnection ( ) throws SQLException { Connection conn = connList. remove ( 0 ) ; / / 增强连接: MyConnectionWrapper connWrapper = new MyConnectionWrapper ( conn , connList ) ; return connWrapper; } / / 编写一个归还连接的方法 : / * public void addBack ( Connection conn ) { connList. add ( conn ) ; } * / } |
l 测试代码