设计模式1-单例模式的8种实现
Posted yuec1998
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式1-单例模式的8种实现相关的知识,希望对你有一定的参考价值。
//1、饿汉式(静态变量)
class Singleton1 {
//构造器私有化
private Singleton1() {
}
private final static Singleton1 instance = new Singleton1();
public static Singleton1 getInstance() {
return instance;
}
}
//2、饿汉式(静态代码块)
class Singleton2 {
private Singleton2() {
}
private static Singleton2 instance;
//静态代码块
static {
instance = new Singleton2();
}
public static Singleton2 getInstance() {
return instance;
}
}
//3、懒汉式(线程不安全)
class Singleton3 {
private Singleton3() {
}
private static Singleton3 instance;
//线程不安全
public static Singleton3 getInstance() {
if (instance == null) {
instance = new Singleton3();
}
return instance;
}
}
//4、懒汉式(线程安全)
class Singleton4 {
private Singleton4() {
}
private static Singleton4 instance;
//加了synchronized,线程安全,效率低
public static synchronized Singleton4 getInstance() {
if (instance == null) {
instance = new Singleton4();
}
return instance;
}
}
//5、懒汉式(线程安全,不良改进版)
class Singleton5 {
private Singleton5() {
}
private static Singleton5 instance;
//有问题的改进版,高并发时候可能存在多个线程都同时进入到if中,而产生多个实例
public static Singleton5 getInstance() {
if (instance == null) {
synchronized (Singleton5.class) {
instance = new Singleton5();
}
}
return instance;
}
}
//6、懒汉式(线程安全,双重检查,推荐版)
class Singleton6 {
private Singleton6() {
}
private static volatile Singleton6 instance;
public static Singleton6 getInstance() {
if (instance == null) {
synchronized (Singleton6.class) {
if (instance == null) {
instance = new Singleton6();
}
}
}
return instance;
}
}
//7、懒汉式(静态内部类,推荐使用)
class Singleton7 {
private Singleton7() {
}
private static class SingletonInstance {
private static final Singleton7 INSTANCE = new Singleton7();
}
//利用类加载机制保证初始化实例时只有一个线程,线程安全
//利用静态内部类特点实现延迟加载,效率高
public static Singleton7 getInstance() {
return SingletonInstance.INSTANCE;
}
}
//8、通过枚举实现,推荐使用
enum SingletonEnum{
INSTANCE;
public void helloWord(){
System.out.println("hello java!");
}
以上是关于设计模式1-单例模式的8种实现的主要内容,如果未能解决你的问题,请参考以下文章