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();
}
}
}
单例的其他实际用例:
- 管理
ThreadPool, ObjectPool, DatabaseConnectionPool
等全局资源 - 集中服务,如
Logging
应用程序数据,具有不同的日志级别,如DEBUG,INFO,WARN,ERROR
等 - Global
RegistryService
,其中不同的服务在启动时注册了一个中心组件。这个全局服务可以充当应用程序的时间 9