单例模式学习笔记

单例模式是一种常用的设计模式,它确保一个类只有一个实例,并提供了全局访问点。

实现单例模式的方法

1. 饿汉式单例模式

在类加载时创建唯一实例,因此线程安全,但可能会浪费资源,因为实例在使用之前就已创建。

javaCopy Code
public class Singleton { private static Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; } }

2. 懒汉式单例模式

延迟创建实例,直到首次使用时。需要考虑线程安全和性能问题。

2.1 线程不安全的懒汉式单例模式

javaCopy Code
public class Singleton { private static Singleton instance = null; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }

如果多个线程同时调用getInstance方法,可能会导致创建多个实例的问题。

2.2 线程安全的懒汉式单例模式

使用synchronized关键字保证线程安全,但会影响性能。

javaCopy Code
public class Singleton { private static Singleton instance = null; private Singleton() {} public synchronized static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }

2.3 双重检查锁定的懒汉式单例模式

在保证线程安全的同时,尽可能减少锁的使用。

javaCopy Code
public class Singleton { private static volatile Singleton instance = null; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }

实例

下面以一个简单的日志记录器为例,演示如何使用单例模式。

javaCopy Code
public class Logger { private static Logger instance = null; private Logger() {} public static Logger getInstance() { if (instance == null) { synchronized (Logger.class) { if (instance == null) { instance = new Logger(); } } } return instance; } public void log(String message) { System.out.println(new Date() + ": " + message); } }

使用示例:

javaCopy Code
public class MyApp { public static void main(String[] args) { Logger logger = Logger.getInstance(); logger.log("Hello, world!"); } }

以上代码会输出类似于以下内容的日志:

Copy Code
Sat Jun 05 21:34:13 CST 2023: Hello, world!