单例模式

73 阅读2分钟

特点

  1. 想确保任何情况下都绝对只有1个实例
  2. 想在程序上表现出只有一个实例

实例程序

public class Singleton {
    private static Singleton singleton = new Singleton();

    private Singleton() {
    }

    public static Singleton getInstance() {
        return singleton;
    }
}
  1. 类中的自身的成员变量要为私有;
  2. 构造器也要私有,防止外界可以直接创建该对象;
  3. 通过指定的方法来获取该唯一的对象即可;

两种实现方式

饿汉式

普通方式

单例实例在类加载时构建

/**
 * 饿汉式
 */
public class HungryStyleSingleton {
    
    // 全局唯一实例
    private static HungryStyleSingleton HungryStyleSingleton = new HungryStyleSingleton();

    // 私有化构造器
    private HungryStyleSingleton() {

    }

    // 获取唯一实例
    public static HungryStyleSingleton getInstance() {
        return HungryStyleSingleton;
    }
}

枚举方式

public enum SingletonEnum {
    INSTANCE;

    public void doSomeThing() {
        System.out.println("枚举方式实现单例");
    }
}
public class Test {
    public static void main(String[] args) {
        SingletonEnum singletonEnum = SingletonEnum.INSTANCE;
        singletonEnum.doSomeThing();
    }
}

懒汉式

单例实例在类第一次被使用的时候构建

非线程安全版本

/**
 * 懒汉式
 */
public class LazyStyleSingleton {
    private static LazyStyleSingleton lazyStyleSingleton = null;
    
    private LazyStyleSingleton() {
        
    }
    
    public LazyStyleSingleton getLazyStyleSingleton() {
        if (lazyStyleSingleton == null) {
            lazyStyleSingleton = new LazyStyleSingleton();
        }
        
        return lazyStyleSingleton;
    }
}

synchronized 线程安全版本

/**
 * 懒汉式
 */
public class LazyStyleSingleton {
    private static LazyStyleSingleton lazyStyleSingleton = null;

    private LazyStyleSingleton() {

    }

    public synchronized LazyStyleSingleton getLazyStyleSingleton() {
        if (lazyStyleSingleton == null) {
            lazyStyleSingleton = new LazyStyleSingleton();
        }

        return lazyStyleSingleton;
    }
}

双重检查锁版本

/**
 * 懒汉式
 */
public class LazyStyleSingleton {

    //volatile保证,当变量被初始化成LazyStyleSingleton实例时,多个线程可以正确处理变量
    private volatile static LazyStyleSingleton lazyStyleSingleton = null;

    private LazyStyleSingleton() {

    }

    public LazyStyleSingleton getLazyStyleSingleton() {
        
        // 双重检查锁
        if (lazyStyleSingleton == null) {
            synchronized (this) {
                if (lazyStyleSingleton == null) {
                    lazyStyleSingleton = new LazyStyleSingleton();
                }
            }
        }
        return lazyStyleSingleton;
    }
}
	

静态内部类方式

/**
 * 懒汉式
 */
public class LazyStyleSingleton {

    // 静态内部实现的单例是懒加载的且线程安全
    private static class SingletonHolder {
        public static final LazyStyleSingleton INSTANCE = new LazyStyleSingleton();
    }

    private LazyStyleSingleton() {

    }

    /**
     * 内部静态类不会自动初始化,只有调用静态内部类的方法,静态域,或者构造方法的时候才会加载静态内部类。
     * @return
     */
    public LazyStyleSingleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}