Java單例模式(Singleton Pattern)是一種創建型設計模式,它確保一個類只有一個實例,并提供一個全局訪問點。單例模式在以下應用場景中非常有用:
public class DatabaseConnection {
private static DatabaseConnection instance;
private Connection connection;
private DatabaseConnection() {
// 初始化數據庫連接
}
public static synchronized DatabaseConnection getInstance() {
if (instance == null) {
instance = new DatabaseConnection();
}
return instance;
}
public Connection getConnection() {
return connection;
}
}
public class Logger {
private static Logger instance;
private PrintWriter writer;
private Logger() {
// 初始化日志記錄器
}
public static synchronized Logger getInstance() {
if (instance == null) {
instance = new Logger();
}
return instance;
}
public void log(String message) {
if (writer == null) {
writer = new PrintWriter(System.out, true);
}
writer.println(message);
}
}
public class ConfigurationManager {
private static ConfigurationManager instance;
private Properties properties;
private ConfigurationManager() {
// 加載配置文件
properties = new Properties();
// 讀取配置文件內容并存儲到properties對象中
}
public static synchronized ConfigurationManager getInstance() {
if (instance == null) {
instance = new ConfigurationManager();
}
return instance;
}
public String getProperty(String key) {
return properties.getProperty(key);
}
}
public class CacheManager {
private static CacheManager instance;
private Map<String, Object> cache;
private CacheManager() {
// 初始化緩存
cache = new HashMap<>();
}
public static synchronized CacheManager getInstance() {
if (instance == null) {
instance = new CacheManager();
}
return instance;
}
public Object get(String key) {
return cache.get(key);
}
public void put(String key, Object value) {
cache.put(key, value);
}
}
public class ThreadPool {
private static ThreadPool instance;
private ExecutorService executorService;
private ThreadPool() {
// 初始化線程池
executorService = Executors.newFixedThreadPool(10);
}
public static synchronized ThreadPool getInstance() {
if (instance == null) {
instance = new ThreadPool();
}
return instance;
}
public void execute(Runnable task) {
executorService.execute(task);
}
}
總之,Java單例模式在許多應用場景中都非常有用,特別是在需要確保一個類只有一個實例并提供全局訪問點的情況下。