享元模式的主要目的是实现对象的共享,即共享池,当系统中对象多的时候可以减少内存的开销,通常与工厂模式一起使用。
例子:
public class ConnectionPool {
private Vector<Connection> pool;
//共有属性
private String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
private String username="briup";
private String password="briup";
private String driver="oracle.jdbc.OracleDriver";
private int poolSize=10;
//这里对instance可以使用一个单例模式
private static ConnectionPool instance = null;
Connection conn = null;
public static ConnectionPool getInstance() {
if(instance==null) {
synchronized (ConnectionPool.class) {
if(instance==null) {
instance = new ConnectionPool();
}
}
}
return instance;
}
private ConnectionPool() {
pool = new Vector<Connection>(poolSize);
for(int i=0;i<poolSize;i++) {
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
pool.add(conn);
//conn.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//把连接对象返回到连接池
public synchronized void release() {
pool.add(conn);
}
//返回连接池中的一个数据库连接
public synchronized Connection getConnection() {
if(pool.size()>0) {
Connection conn = pool.get(0);
pool.remove(conn);
return conn;
}else {
return null;
}
}
public static void main(String[] args) {
System.out.println(ConnectionPool.getInstance().getConnection());
System.out.println(ConnectionPool.instance.pool.size());
}
}