package com.offer;
/**
* @authore Xavier
* @description 单例模式有一下特点:
* 1、单例类只能有一个实例。
* 2、单例类必须自己自己创建自己的唯一实例。
* 3、单例类必须给所有其他对象提供这一实例。
* @date 2018/7/17
*/
public class Singleton {
private Singleton() {
}
;
/**
* 考虑线程安全兼顾效率的写法
* 双重检查锁
*/
private static volatile Singleton singleton = null;
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
/**
* 静态内部类法
*/
private static class Holder {
private static Singleton singleton = new Singleton();
}
public static Singleton getSingleton2() {
if (singleton == null) {
return Holder.singleton;
}
return singleton;
}
/**
* 枚举类写法-推荐的写法
*/
// public enum Singleton {
// INSTANCE;
// private String name;
// public String getName(){
// return name;
// }
// public void setName(String name){
// this.name = name;
// }
// }
}