通过单例模式可以保证系统中,应用该模式的类一个类只有一个实例。即一个类只有一个对象实例
1.懒汉式
//懒汉式 , 线程安全 public class Single { //创建实例对象并且初始化 private static Single instance = null; //构造器私有化 private Single() { } //获取唯一的可用的对象 public static synchronized Single getInstance() { if(instance == null) { instance = new Single(); } return instance; } public static void main(String[] args) { Single s1 = Single.getInstance(); Single s2 = Single.getInstance(); System.out.println(s1 == s2); } }
2.饿汉式
//饿汉式 public class Single { private static final Single instance = new Single(); //构造器私有化 private Single() { } //获取唯一的可用的对象 public static Single getInstance() { return instance; } public static void main(String[] args) { Single s1 = Single.getInstance(); Single s2 = Single.getInstance(); System.out.println(s1 == s2); } }
3.双重锁形式:
//双重锁形式 public class Single { private static volatile Single instance = null; //构造器私有化 private Single() { } //获取唯一的可用的对象 public static Single getInstance() { if(instance == null) { synchronized (Single.class) { if(instance == null) { instance = new Single(); } } } return instance; } public static void main(String[] args) { Single s1 = Single.getInstance(); Single s2 = Single.getInstance(); System.out.println(s1 == s2); } }
一般用第三种