设计模式 | 单例设计模式(五种实现)
程序员文章站
2024-01-24 09:00:22
...
定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
- 单例设计模式的五种实现
- 饿汉
- 懒汉(线程不安全)
- 懒汉(线程安全)
- DCL(双重检查)
- 登记式(利用静态域的延时加载)
package com.darwin.patterns.create;
import java.util.Objects;
/**
* 单例设计模式
*/
public class SingletonPatternDemo {
public static void main(String[] args) {
}
}
/**
* 饿汉
*/
class Singleton1 {
private static final Singleton1 singleton1 = new Singleton1();
private Singleton1() {
}
public static Singleton1 getInstance() {
return singleton1;
}
}
/**
* 懒汉,线程不安全
*/
class Singleton2 {
private static Singleton2 singleton2;
private Singleton2() {
}
public static Singleton2 getInstance() {
if (Objects.isNull(singleton2)) {
singleton2 = new Singleton2();
}
return singleton2;
}
}
/**
* 懒汉,线程不安全
*/
class Singleton3 {
private static Singleton3 singleton3;
private Singleton3() {
}
public static synchronized Singleton3 getInstance() {
if (Objects.isNull(singleton3)) {
singleton3 = new Singleton3();
}
return singleton3;
}
}
/**
* DCL双重检查
*/
class Singleton4 {
private static Singleton4 singleton4;
private Singleton4() {
}
public static Singleton4 getInstance() {
if (Objects.isNull(singleton4)) {
synchronized (Singleton4.class) {
if (Objects.isNull(singleton4)) {
singleton4 = new Singleton4();
}
}
}
return singleton4;
}
}
/**
* 登记式/静态内部类
*/
class Singleton5 {
private static class SingletonHolder {
private static final Singleton5 INSTANCE = new Singleton5();
}
private Singleton5() {
}
public static Singleton5 getInstance() {
return Singleton5.SingletonHolder.INSTANCE;
}
}