单例模式的作用或者优点
单例模式可以保证使用该模式的类在系统中永远只有一个实例,避免多个实例存在引起的逻辑错误。
单例模式的六种实现方式
按创建单例的时机,又可以分为在类初始化的时候创建和按需延时创建
a.在类初始化的时候创建
1.饿汉式,线程安全
public class Singleton {
//饿汉式
private static Singleton singleton = new Singleton();
private Singleton(){}
public static Singleton getSingleton(){
return singleton;
}
}
2.枚举,线程安全
public enum Singleton{
INSTANCE
}
b.按需延时创建
public class Singleton{
//懒汉式
private static Singleton singleton = null;
private Singleton(){}
public static Singleton getSingleton(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
public class Singleton{
//懒汉式同步锁1
private static Singleton singleton = null;
private Singleton(){}
public static synchronized Singleton getSingleton(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
public class Singleton{
//懒汉式同步锁2
private static Singleton singleton = null;
private Singleton(){}
public static Singleton getSingleton(){
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
return singleton;
}
}
public class Singleton{
//懒汉式双重校验锁
private static Singleton singleton = null;
private Singleton(){}
public static Singleton getSingleton(){
if(singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
public class Singleton{
//静态内部类
private static class Singleton2{
private static Singleton singleton = new Singleton();
}
private Singleton(){}
public static Singleton getSingleton(){
return Singleton2.singleton;
}