欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

单例模式创建的几种方式

程序员文章站 2022-07-14 09:25:09
...

单例模式

饿汉式两种方式

/**
 * 单例
 * 静态常量饿汉式
 */
public class Demo1 {
    public static void main(String[] args){
        Singleton singleton2 = Singleton.GetInstance();
        Singleton singleton1 = Singleton.GetInstance();
        System.out.println(singleton1==singleton2);
    }

}
//静态常量饿汉式
class Singleton{
    private Singleton(){
    }

    private final static Singleton instance = new Singleton();

    public static Singleton  GetInstance(){
        return instance;
    }
}

/**
 * 单例
 * 静态常量饿汉式
 */
public class Demo2 {
    public static void main(String[] args){
        Singleton2 singleton2 = Singleton2.GetInstance();
        Singleton2 singleton1 = Singleton2.GetInstance();
        System.out.println(singleton1==singleton2);
    }

}

//静态常量饿汉式
class Singleton2{
    private Singleton2(){
    }

    private  static Singleton2 instance;
    static {
        instance = new Singleton2();
    }
    public static Singleton2 GetInstance(){
        return instance;
    }
}

懒汉式两种方式

/**
 * 单例双重检查
 * 线程安全懒汉式
 */
public class Demo5 {
    public static void main(String[] args) {
        Singleton5 singleton2 = Singleton5.GetInstance();
        Singleton5 singleton1 = Singleton5.GetInstance();
        System.out.println(singleton1 == singleton2);
    }
}

class Singleton5 {

    private static volatile Singleton5 instance;

    private Singleton5() {}

    public static Singleton5 GetInstance() {
        if(instance==null){
            synchronized (Singleton5.class){
                if(instance==null){
                    instance = new Singleton5();
                }
            }
        }
        return instance;
    }
}

/**
 * 单例静态内部类
 * 线程安全懒汉式
 */
public class Demo6 {
    public static void main(String[] args) {
        Singleton6 singleton2 = Singleton6.GetInstance();
        Singleton6 singleton1 = Singleton6.GetInstance();
        System.out.println(singleton1 == singleton2);
    }
}


class Singleton6 {

    private static  Singleton6 instance;

    private Singleton6() {}

    static class InnerClass{
        private static final  Singleton6 instance = new Singleton6();
    }
    public static Singleton6 GetInstance() {
        return instance = InnerClass.instance;
    }
}

使用场景

需要频繁创建与销毁的对象、工具类,如数据源,session工厂。