java的单例模式
时间: 2023-06-29 08:14:15 浏览: 119
单例模式是一种常用的创建模式,它保证一个类仅有一个实例,并提供一个访问它的全局访问点。
Java中单例模式的实现方式有以下几种:
1. 饿汉式单例模式(线程安全):
```java
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
```
2. 懒汉式单例模式(非线程安全):
```java
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
```
3. 懒汉式单例模式(线程安全,但性能较低):
```java
public class Singleton {
private static Singleton instance;
private Singleton() {}
public synchronized static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
```
4. 双重检查锁定单例模式(线程安全,且性能较高):
```java
public class Singleton {
private volatile static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
```
5. 静态内部类单例模式(线程安全,但是需要额外的内存):
```java
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
```
阅读全文