1.饿汉式
public class Singleton {
private static Singleton instance
= new Singleton();
private Singleton(){
}
public static Singleton
getInstance(){
return instance
;
}
}
2.懒汉式
public class Singleton {
private static Singleton instance
= null
;
private Singleton(){
}
public static Singleton
getInstance(){
if (null
== instanc
){
instance
= new Singleton();
}
return instance
;
}
}
3.懒汉式+同步方法
public class Singleton {
private static Singleton instance
= null
;
private Singleton(){
}
public static synchronized Singleton
getInstance(){
if (null
== instanc
){
instance
= new Singleton();
}
return instance
;
}
}
4.Double-Check
public class Singleton {
private static Singleton instance
= null
;
private Singleton(){
}
public static Singleton
getInstance(){
if (null
== instance
){
synchronized (Singleton
.class){
if (null
== instance
){
instance
= new Singleton();
}
}
}
return instance
;
}
}
5.Volatile+Double-Check
public class Singleton {
private volatile static Singleton instance
= null
;
private Singleton(){
}
public static Singleton
getInstance(){
if (null
== instance
){
synchronized (Singleton
.class){
if (null
== instance
){
instance
= new Singleton();
}
}
}
return instance
;
}
}
6.Holder方式
public class Singleton {
private Singleton(){
}
private static class Holder {
private static Singleton instance
= new Singleton();
}
public static Singleton
getInstance(){
return Holder
.instance
;
}
}
7.枚举方式
public enum Singleton
{
INSTANCE
;
private Singleton(){
System
.out
.println("INSTACE will be initialized immediately");
}
private static void method() {
}
public static Singleton
getInstance(){
return INSTANCE
;
}
}
转载请注明原文地址: https://lol.8miu.com/read-21531.html