设计模式-单例模式
Posted Write the Code Change the Worl
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式-单例模式相关的知识,希望对你有一定的参考价值。
单例模式的五种实现写法:懒汉、饿汉、双重检验锁、静态内部类、枚举。线程安全的实现方式
懒汉式:
public class Singleton {
private static Singleton instatnce;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instatnce == null)
instatnce=new Singleton();
return instatnce;
}
}
双重检验锁:
public class Singleton {
private static Singleton instatnce;
private Singleton(){}
public static Singleton getInstance(){
if(instatnce == null){
synchronized(Singleton.class){
if(instatnce == null)
instatnce=new Singleton();
}
}
return instatnce;
}
}
饿汉式:
public class Singleton {
private static Singleton instatnce=new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instatnce;
}
}
静态内部类:
public class Singleton {
private static class SingletonHolder{
private static final Singleton INSTANCE = new Singleton();
}
private Singleton(){}
public static final Singleton getInstance(){
return SingletonHolder.INSTANCE;
}
}
枚举:
public enum EasySingleton {
INSTANCE;
}
以上是关于设计模式-单例模式的主要内容,如果未能解决你的问题,请参考以下文章