单例:一个类无论怎么创建,都只有一个对象
1. 在成员变量位置创建对象
2. 私有构造方法
3. 提供公共的访问方式获取对象
demo实例:
------------------------------------------------------------------------
/*饿汉式 线程安全*/ public class Single { private static Single single = new Single(); private Single(){ } public static Single getSingle(){ return single; } }
测试类:
public class Test { public static void main(String[] args) { Single single1 = Single.getSingle(); Single single2 = Single.getSingle(); /*创建两个实例,如果地址值一样,则证明 该类只创建一次 符合单例*/ System.out.println(single1); System.out.println(single2); } }
测试结果:
com.csdn.singleton.Single@1540e19d
com.csdn.singleton.Single@1540e19d
-------------------------------------------------------------------------------------
懒汉式:单线程
/*懒汉式 线程不安全,适用于单线程*/ public class Singleton { private static Singleton instance = null; private Singleton() { } public static Singleton getSingleton(){ if(instance == null){ instance = new Singleton(); } return instance; } } 测试类:
public class Test { public static void main(String[] args) { Singleton single1 = Singleton.getSingleton(); Singleton single2 = Singleton.getSingleton(); /*创建两个实例,如果地址值一样,则证明 该类只创建一次 符合单例*/ System.out.println(single1); System.out.println(single2); } } 测试结果: com.csdn.singleton.Singleton@1540e19d com.csdn.singleton.Singleton@1540e19d---------------------------------------------------------------------
懒汉式:多线程
/*懒汉模式 线程安全 适用于多线程 */ public class Singleton2 { private static Singleton2 instance; private Singleton2() { } public static Singleton2 getSingleton2(){ /*这层判断目的:当一条线程创建了对象,其他线程就不用再获取锁,再判断创建实例。提高效率*/ if(instance == null) { /*加同步锁,防止多线程访问出现创建多个实例*/ synchronized (Singleton2.class) { if (instance == null) { instance = new Singleton2(); } } } return instance; } }测试类:
public class Test { public static void main(String[] args) { Singleton2 single1 = Singleton2.getSingleton2(); Singleton2 single2 = Singleton2.getSingleton2(); /*创建两个实例,如果地址值一样,则证明 该类只创建一次 符合单例*/ System.out.println(single1); System.out.println(single2); } } 结果: com.csdn.singleton.Singleton2@1540e19d com.csdn.singleton.Singleton2@1540e19d