What are static factory methods?

前端 未结 14 747
粉色の甜心
粉色の甜心 2020-11-22 06:08

What\'s a \"static factory\" method?

14条回答
  •  盖世英雄少女心
    2020-11-22 06:41

    We avoid providing direct access to database connections because they're resource intensive. So we use a static factory method getDbConnection that creates a connection if we're below the limit. Otherwise, it tries to provide a "spare" connection, failing with an exception if there are none.

    public class DbConnection{
       private static final int MAX_CONNS = 100;
       private static int totalConnections = 0;
    
       private static Set availableConnections = new HashSet();
    
       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);
         //...
       }
    }
    

提交回复
热议问题