使用饿汉和懒汉模式改造
时间: 2024-02-23 21:51:14 浏览: 24
饿汉模式是指在程序运行时就创建对象实例,而懒汉模式是指在需要使用对象实例时才创建,下面是使用饿汉和懒汉模式改造的示例。
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 synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
```
在懒汉模式中,getInstance()方法需要加上synchronized关键字,保证线程安全。此外,还可以通过双重检查锁定来优化懒汉模式,避免每次访问都加锁,具体实现可以参考以下代码:
```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;
}
}
```
在双重检查锁定中,需要使用volatile关键字来保证线程安全。这种方式既保证了懒加载,也保证了线程安全和性能。