2019独角兽企业重金招聘Python工程师标准>>>
享元模式(flyweight):
主要目的是实现对象的共享,即共享池,当系统中对象多的时候可以减少内存的开销,通常与工厂模式一起使用。
示例:
连接池(享元模式)ConnectionPool.java
/**
* 连接池(享元模式)
*
* @author Kevin
* @date 2016-3-15
*/
public class ConnectionPool {
private static ConnectionPool instance = null;
/* 连接池 */
private List<Connection> pool;
/*公有属性*/
private String url = "jdbc:mysql://localhost:3306/test";
private String username = "root";
private String password = "root";
private String driverClassName = "com.mysql.jdbc.Driver";
private int poolSize = 100;
private Connection conn = null;
/**
* 私有构造方法,做一些初始化工作
*
* @author Kevin
*/
private ConnectionPool() {
List<Connection> connectionList = new ArrayList<Connection>(poolSize);
pool = Collections.synchronizedList(connectionList);
for (int i = 0; i < poolSize; i++) {
try {
Class.forName(driverClassName);
conn = DriverManager.getConnection(url, username, password);
pool.add(conn);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 返回连接到连接池
*
* @author Kevin
*/
public synchronized void release() {
pool.add(conn);
}
/**
* 获取连接池中的一个数据库连接
*
* @author Kevin
*/
public synchronized Connection getConnection() {
if (pool.size() > 0) {
Connection conn = pool.get(0);
pool.remove(conn);
return conn;
} else {
return null;
}
}
}