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单例模式在许多应用场景中都非常有用,特别是在需要确保一个类只有一个实例并提供全局访问点的情况下。