单例模式的特点:
1、只有一个实例。
2、必须自己创建实例。
3、必须给其他所有对象提供该实例。
单例模式的实现:
一 、 懒汉式
public class TestSingleton { private static TestSingleton testSingleton = null; private TestSingleton(){ }; public static TestSingleton getTestSingleton(){ if(testSingleton==null){ testSingleton = new TestSingleton(); } return testSingleton; } }
升级版 (线程安全的)
public class TestSingleton { private static TestSingleton testSingleton = null; private TestSingleton(){ }; public static synchronized TestSingleton getTestSingleton(){ if(testSingleton==null){ testSingleton = new TestSingleton(); } return testSingleton; } }
二、双重检查锁定
public class TestSingleton { private volatile static TestSingleton testSingleton = null; private TestSingleton(){ }; public static TestSingleton getTestSingleton(){ if(testSingleton==null){ synchronized (TestSingleton.class){ if(testSingleton==null){ testSingleton = new TestSingleton(); } } } return testSingleton; } }
三、静态内部类
public class TestSingleton { private TestSingleton(){ } private static class TestSingletonHolder { private volatile static TestSingleton testSingleton = new TestSingleton(); } public static TestSingleton getTestSingleton(){ return TestSingletonHolder.testSingleton; } }
四、饿汉式
public class TestSingleton { private volatile static TestSingleton testSingleton = new TestSingleton(); private TestSingleton(){ } public static TestSingleton getTestSingleton(){ return testSingleton; } }
五 枚举
public enum TestSingleton { testSingleton; /** * 操作 */ public void getTestSingleton(){ } }