Java设计模式- Singleton

作者: 何恩 | 来源:发表于2014-06-15 20:37 被阅读6833次

Java 设计模式 单例模式 Singleton


1.懒汉(线程安全)

//懒汉
public class Singleton {
    private static Singleton singleton;

    private Singleton() {

    }

    public static synchronized Singleton getSingleton() {
        if (singleton == null) {
            singleton = new Singleton();
        }

        return singleton;
    }
}

2.饿汉

//饿汉
public class Singleton {
    private static final Singleton singleton = new Singleton();

    private Singleton () {

    }

    public static Singleton getSingleton() {
        return singleton;
    }
}

3.静态内部类

//静态内部类
public class Singleton {
    private static class SingletonHolder {
        private static final Singleton singleton = new Singleton();
    }

    private Singleton() {

    }

    public static Singleton getSingleton() {

        return SingletonHolder.singleton;
    }
}

4.枚举

//枚举
public enum Singleton {
    INSTANCE;

    public void whateverMethod() {

    }
}

5.double-lock

//double-lock
public class Singleton {
    private volatile static Singleton singleton;

    private Singleton() {

    }

    public static Singleton getSingleton() {
        if (singleton == null) {
            synchronized(Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }

        return singleton;
    }
}

相关文章

  • JAVA设计模式 - 单例模式

    JAVA设计模式 - 单例模式 单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一...

  • 设计模式——单例模式

    设计模式——单例模式 单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一,这种类型...

  • 单例模式

    3、单例模式(Singleton) 单例对象(Singleton)是一种常用的设计模式。在Java应用中,单例对象...

  • 设计模式

    单例模式 单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式...

  • 设计模式-单例模式(Singleton)

    单例模式(Singleton) 单例对象(Singleton)是一种常用的设计模式。在Java应用中,单例对象能保...

  • 设计模式《一》单例模式

    单例模式 单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属...

  • 设计模式之单例模式详解(附源代码)

    单例模式 单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属...

  • Java设计模式---单例模式

    单例模式 单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属...

  • 单例模式

    单例模式 单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属...

  • Java基础一一设计模式:单例模式的运用

    单例模式 单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属...

网友评论

    本文标题:Java设计模式- Singleton

    本文链接:https://www.haomeiwen.com/subject/qqcjtttx.html