`
zhu1xu2
  • 浏览: 4527 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

JAVA设计模式(四)单例模式

阅读更多
单例模式 确保一个类只有一个实例,并提供一个全局访问站点。

类图:


1.线程不安全的单例模式
/**
 * 单例模式(线程不安全)
 */
public class SingletonTest {

    private static SingletonTest instance;

    private SingletonTest() {
    }

    public static SingletonTest getInstance() {
        if (instance == null) {
            instance = new SingletonTest();
        }
        return instance;
    }
}


2.“懒汉”模式
/**
 * 单例模式(线程安全、每次调用都同步getInstance方法,影响效率)
 */
public class SingletonTest {

    private static SingletonTest instance;

    private SingletonTest() {
    }

    public static synchronized SingletonTest getInstance() {
        if (instance == null) {
            instance = new SingletonTest();
        }
        return instance;
    }
}


3.“饿汉”模式
/**
 * 单例模式(线程安全、JVM加载类时马上创建实例)
 */
public class SingletonTest {

    private static SingletonTest instance = new SingletonTest();

    private SingletonTest() {
    }

    public static SingletonTest getInstance() {
        return instance;
    }
}


4.双重检查加锁
/**
 * 单例模式(线程安全)
 */
public class SingletonTest {

    private volatile static SingletonTest instance;

    private SingletonTest() {
    }

    public static SingletonTest getInstance() {
        if (instance == null) {
            synchronized (SingletonTest.class) {
                if(instance == null) {
                    instance = new SingletonTest();
                }
            }
        }
        return instance;
    }
}
  • 大小: 4.6 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics