1:单实例类
public class ConnectionPool {
//only one instance is needed
private static ConnectionPool instance;
private ConnectionPool() {
System.out.println("Createing the single instance of connection pool");
}
public static ConnectionPool getInstance() {
if(instance != null) {
System.out.println("Getting existing instance of connection pool ");
return instance;
} else {
instance = new ConnectionPool();
return instance;
}
}
public static void main(String args[]) {
System.out.println("Get connection pool first time");
ConnectionPool cPool = ConnectionPool.getInstance();
System.out.println("Get Connection pool second time ");
ConnectionPool annotherPool = ConnectionPool.getInstance();
}
}
适合于数据库连接池的使用,但是单实例很难扩展,,应该呗设计为并行执行。因为多线程将访问同一个单实例对象。