1.单例模式
- 饿汉式(静态常量)
public class Singleton {
private final static Singleton INSTANCE = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return INSTANCE;
}
}
优点:这种写法比较简单,就是在类装载的时候就完成实例化。避免了线程同步问题。
缺点:在类装载的时候就完成实例化,没有达到Lazy Loading的效果。如果从始至终从未使用过这个实例,则会造成内存的浪费。
- 饿汉式(静态代码块)
public class Singleton{
private static INATANCE;
static{
INATANCE = new Singleton()
}
private Singleton(){}
public static Singleton getInstance(){
return INSTANCE;
}
}
- 懒汉式
public class Singleton{
private static instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
优点:可以实现lazy loading
缺点:线程不安全
- 懒汉式
public class Singleton{
private static instance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
优点:lazy loading 和 线程同步
缺点:效率低
+懒汉式
public class Singleton{
private static instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null){
synchronized(Singleton.class){
instance = new Singleton();
}
}
return instance;
}
}
缺点:可以无法保证只有一个实例
- 双重检查
public class Singleton{
private static instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
优点:效率高,进程同步,lazy loading
- 静态内部类
public class Singleton{
private Singleton(){}
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonInstance.INSTANCE;
}
}
类的静态属性只会在第一次加载类的时候初始化,所以在这里,JVM帮助我们保证了线程的安全性,在类进行初始化时,别的线程是无法进入的。
优点:避免了线程不安全,延迟加载,效率高。
- 枚举
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}
网友评论