什么是“静态工厂”方法?
我们避免提供对数据库连接的直接访问,因为它们是资源密集型的。getDbConnection因此,如果我们低于限制,我们使用静态工厂方法创建连接。否则,它会尝试提供“备用”连接,如果没有则失败并出现异常。
getDbConnection
public class DbConnection{ private static final int MAX_CONNS = 100; private static int totalConnections = 0; private static Set<DbConnection> availableConnections = new HashSet<DbConnection>(); private DbConnection(){ // ... totalConnections++; } public static DbConnection getDbConnection(){ if(totalConnections < MAX_CONNS){ return new DbConnection(); }else if(availableConnections.size() > 0){ DbConnection dbc = availableConnections.iterator().next(); availableConnections.remove(dbc); return dbc; }else { throw new NoDbConnections(); } } public static void returnDbConnection(DbConnection dbc){ availableConnections.add(dbc); //... } }