单例模式

单例模式的适用场景:各种管理类、各种工厂类

实现方式:

饿汉式:
优点:简洁,易懂,个人更倾向实际中使用这种
缺点:每次类加载时就会实例化 ,不能防止反序列化

package com.example.demo;

public class Singleton1 {

    private static final Singleton1 INSTANCE = new Singleton1();

    private Singleton1(){

    }

    public static Singleton1 getInstance(){
        return INSTANCE;
    }

    public static void main(String[] args) {
        for(int i=0; i<100; i++) {
            new Thread(()->{
                System.out.println(Singleton1.getInstance().hashCode());
            }).start();
        }
    }
}

懒汉式
缺点:加锁效率低

package com.example.demo;

public class Singleton2 {
    private static volatile Singleton2 INSTANCE;
    private Singleton2(){

    }

    public static Singleton2 getInstance(){
        //双重检查,第一层是为了如果已经实例化其他线程没必要走到加锁那一步
        if(INSTANCE == null) {
            synchronized (Singleton2.class) {
                if(INSTANCE == null) {
                    INSTANCE = new Singleton2();
                }
            }
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        for(int i=0; i<100; i++) {
            new Thread(()->{
                System.out.println(Singleton2.getInstance().hashCode());
            }).start();
        }
    }
}

静态内部类实现
缺点:可以被反序列化

package com.example.demo;

public class Singleton3 {
    private Singleton3(){

    }
    private static class Singleton3Holder{
        private final static Singleton3 INSTANCE = new Singleton3();
    }

    public static Singleton3 getInstance(){
        return Singleton3Holder.INSTANCE;
    }

    public static void main(String[] args) {
        for(int i=0; i<100; i++) {
            new Thread(()->{
                System.out.println(Singleton3.getInstance().hashCode());
            }).start();
        }
    }
}

枚举方式实现
解决了线程问题和反序列化问题,传说中最完美方式

package com.example.demo;

public enum Singleton4 {
    INSTANCE;

    public static void main(String[] args) {
        for(int i=0; i<100; i++) {
            new Thread(()->{
                System.out.println(Singleton4.INSTANCE.hashCode());
            }).start();
        }
    }
}

你可能感兴趣的:(单例模式)