设计模式--池技术与策略模式

package designpattern.pool;

import designpattern.staticagent.MyConnecntion;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ConnectionPool {

    private static List connections=new ArrayList<>();

    static {
        for (int i=0;i<10;i++){
            //可以考虑dbcp,c3p0的配置,进行设置
            Connection connection=new MyConnecntion();
            connections.add(connection);
        }
    }

    public static synchronized Connection getConnection() throws SQLException {
        for(Connection connection:connections){
            MyConnecntion myConnecntion=(MyConnecntion)connection;
            if(!myConnecntion.isClosed()){
                return myConnecntion;
            }
        }
        //尝试等待一会在获取
        return null;
    }

    public static synchronized void closeConnections(){
        for(Connection connection:connections){
            MyConnecntion myConnecntion=(MyConnecntion)connection;
            myConnecntion.setClose(true);
        }
    }
}

package designpattern.pool;

import java.sql.ResultSet;

public interface RwoMapper {
     Object mapRow(ResultSet resultSet);
}
package designpattern.pool;

import javax.swing.tree.RowMapper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCTemplate {

    public void update(String sql,String...params){
        try {
            Connection connection=ConnectionPool.getConnection();
            connection.prepareStatement(sql,params);
            PreparedStatement preparedStatement=connection.prepareStatement(sql);
            for (int i=0;i

 

你可能感兴趣的:(设计模式)