Mysql 连接池调用完成后close代理方法引出的设计模式

设计模式:如果一个类不足以完成某个功能之时

1.写一个子类,覆盖close方法,增强应用功能

2、写一个connection的包装类,增强close方法

3、用动态代理,返回一个代理对象出去,拦截close方法的调用,对close进行增强

public abstract class JdbcPool implements DataSource {

    private static LinkedList<Connection> list = new LinkedList<Connection>();
    
    static{
        try{
            InputStream in = JdbcPool.class.getClassLoader().getResourceAsStream("db.properties");
            Properties prop = new Properties();
            prop.load(in);
            
            String driver = prop.getProperty("driver");
            String url = prop.getProperty("url");
            String username = prop.getProperty("username");
            String password = prop.getProperty("password");
            
            Class.forName(driver);
            
            for(int i=0;i<10;i++){
                Connection conn = DriverManager.getConnection(url, username, password);
                System.out.println("获取到了链接" + conn);
                list.add(conn);
            }
            
        }catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }
    
    /*
    1.写一个子类,覆盖close方法
    2、写一个connection的包装类,增强close方法
    3、用动态代理,返回一个代理对象出去,拦截close方法的调用,对close进行增强
    */
    
    public Connection getConnection() throws SQLException {
        
        //proxyConnection.commit()  proxyConnection.rollback
        if(list.size()>0){
            final Connection conn = list.removeFirst();   //myconnection.commit
            System.out.println("池大小是" + list.size());
            return (Connection) Proxy.newProxyInstance(JdbcPool.class.getClassLoader(), conn.getClass().getInterfaces(), new InvocationHandler(){

                public Object invoke(Object proxy, Method method, Object[] args)
                        throws Throwable {
                    if(!method.getName().equals("close")){
                        return method.invoke(conn, args);
                    }else{
                        list.add(conn);
                        System.out.println(conn + "被还给池了!!");
                        System.out.println("池大小为" + list.size());
                        return null;
                    }     
                }
                
            });
            
        }else{
            throw new RuntimeException("对不起,数据库忙");
        }
        
    }

用包装设计模式对某个对象进行增强
1.写一个类,实现与被增强对象(mysql的connection)相同的接口
2、定义一个变量,指向被增强对象
3、定义一个构造方法,接收被增强对象
4、覆盖想增强的方法
5、对于不想增强的方法,直接调用被增强对象的方法
 */

posted @ 2013-07-13 13:57  亂舞春秋  阅读(322)  评论(0编辑  收藏  举报