单例模式
单例模式的作用单例模式的类型饿汉式懒汉式登记式
单例模式的作用
单例模式:是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。
单例模式的要点:一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行 向整个系统提供这个实例。
单例模式的作用:一是,解决多线程并发访问的问题。二是节约系统内存,提交系统运行的效率,提高系统性能。
单例模式的类型
饿汉式
public class Singleton {
private static Singleton instance
= new Singleton();
private Singleton
(){}
public static Singleton
getInstance() {
return instance
;
}
}
好处:不会有多线程问题 使用简单 坏处:一开始就初始化对象,会造成浪费 一般程序都会按照自己需要进行初始化对象 引出按需初始化对象的懒加载方式(如下)
懒汉式
public class Singleton {
private static Singleton instance
;
private Singleton
(){}
public static synchronized Singleton
getInstance() {
if (instance
== null
) {
instance
= new Singleton();
}
return instance
;
}
}
登记式
1 public class Singleton {
2 private static class SingletonHolder {
3 private static final Singleton INSTANCE
= new Singleton();
4 }
5 private Singleton
(){}
6 public static final Singleton
getInstance() {
7 return SingletonHolder
.INSTANCE
;
8 }
9 }