Lazy Singleton 在 java 中的實際例子

Singleton 模式的現實生活用例;

如果你正在開發客戶端 - 伺服器應用程式,則需要單個 ConnectionManager,它管理客戶端連線的生命週期。

ConnectionManager 中的基本 API:

registerConnection:新增與現有連線列表的新連線

closeConnection:關閉客戶端或伺服器觸發的事件的連線

broadcastMessage:有時,你必須向所有訂閱的客戶端連線傳送訊息。

我沒有提供原始碼的完整實現,因為示例將變得非常冗長。在高階別,程式碼將是這樣的。

import java.util.*;
import java.net.*;

/* Lazy Singleton - Thread Safe Singleton without synchronization and volatile constructs */
final class  LazyConnectionManager {
    private Map<String,Connection> connections = new HashMap<String,Connection>();
    private LazyConnectionManager() {}
    public static LazyConnectionManager getInstance() {
        return LazyHolder.INSTANCE;
    }
    private static class LazyHolder {
        private static final LazyConnectionManager INSTANCE = new LazyConnectionManager();
    }

    /* Make sure that De-Serailzation does not create a new instance */
    private Object readResolve()  {
        return LazyHolder.INSTANCE;
    }
    public void registerConnection(Connection connection){
        /* Add new connection to list of existing connection */
        connections.put(connection.getConnectionId(),connection);
    }
    public void closeConnection(String connectionId){
        /* Close connection and remove from map */
        Connection connection = connections.get(connectionId);
        if ( connection != null) {
            connection.close();
            connections.remove(connectionId);
        }
    }
    public void broadcastMessage(String message){
        for (Map.Entry<String, Connection> entry : connections.entrySet()){
            entry.getValue().sendMessage(message);            
        }
    }    
}

示例伺服器類:

class Server implements Runnable{
    ServerSocket socket;
    int id;
    public Server(){
        new Thread(this).start();
    }
    public void run(){
        try{
            ServerSocket socket = new ServerSocket(4567);
            while(true){
                Socket clientSocket = socket.accept();
                ++id;
                Connection connection = new Connection(""+ id,clientSocket);
                LazyConnectionManager.getInstance().registerConnection(connection);    
                LazyConnectionManager.getInstance().broadcastMessage("Message pushed by server:");
            }
        }catch(Exception err){
            err.printStackTrace();
        }
    }
    
}

單例的其他實際用例:

  1. 管理 ThreadPool, ObjectPool, DatabaseConnectionPool 等全域性資源
  2. 集中服務,如 Logging 應用程式資料,具有不同的日誌級別,如 DEBUG,INFO,WARN,ERROR
  3. Global RegistryService,其中不同的服務在啟動時註冊了一箇中心元件。這個全域性服務可以充當應用程式的時間 9