1  主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。

一 :第一种 饿汉式(预加载)

 public class Singleton {
private Singleton(){}////在自己内部定义自己一个实例,注意这是private
private static Singleton instance = new Singleton(); public static Singleton getInstance() {
return instance;
} public static void main(String[] args) {
Singleton sing=Singleton.getInstance();
System.out.println(sing);
}
}

二:第二种 饿汗式(变种)

 1 public class Singleton {
2 private Singleton (){}
3 private Singleton instance = null;
4 static {
5 instance = new Singleton();
6 }
7
8 public static Singleton getInstance() {
9 return this.instance;
10 }
11 public static void main(String[] args) {
12 Singleton sing=Singleton.getInstance();
13 System.out.println(sing);
14 }
15 }

三:第三种 懒汉式(懒加载 线程不安全

 public class Singleton {
private Singleton(){}
private static Singleton instance; public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
} public static void main(String[] args) {
Singleton sing=Singleton.getInstance();
System.out.println(sing);
}
}

四:第四种 懒汉式(单线程安全)

 public class Singleton {
private Singleton(){}
private static Singleton instance; public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
} public static void main(String[] args) {
Singleton sing=Singleton.getInstance();
System.out.println(sing);
}
}

五:第五种  静态内部类

 public class Singleton {
private Singleton (){}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
} public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
//因为SingletonHolder类没有被主动使用,只有显示通过调用getInstance方法时,才会显示装载SingletonHolder类,从而实例化instance。 }

六:第六种  双重校验锁

 public class Singleton {
private volatile static Singleton instance=null;
private Singleton (){}
public static Singleton getInstance() {
if (instance== null) {
synchronized (Singleton.class) {
if (instance== null) {
instance= new Singleton();
}
}
}
return instance;
}
}

这种方式只是在初始化Singleton那部分代码的时候添加同步锁,这样提高了效率。

05-11 13:58