单例模式概念
就是指一个类确保只有一个实体,并且自行实例化一个实例提供给整个系统。
1.1特点
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
总结:单例模式确保了全局对象的唯一性。
1.2单例模式实现的3种方式
饿汉式,懒汉式,双重检查
1.2.1 饿汉式
静态常量
这种写法比较简单,就是在类装载的时候就完成实例化。避免了线程同步问题。
在类装载的时候就完成实例化,如果整个系统都没有用到这个实例就会造成内存的资源浪费。
public class Person{
private final static Person instance = new Person();
private Person(){}
public static Person getInstance(){
return instance;
}
}
静态代码块
public class Person {
private static Person instance;
static {
instance = new Person();
}
private Person(){}
public static Person getInstance(){
return instance;
}
}
1.2.2 懒汉式
public class Person {
private static Person instance;
private Person(){}
public static Person getInstance(){
if (instance == null){
instance = new Person();
}
return instance;
}
}
上面这种方法线程不安全,不推荐使用
就是说单线程还行,多线程一起的话就会产生多个实例
public class Person {
private static Person instance;
private Person(){}
public static synchronized Person getInstance(){
if (instance == null){
instance = new Person();
}
return instance;
}
}
此法再上面的基础上多加了一个关键字synchronized,也就是加锁。虽然线程安全了,但是效率也就变差了。本人不推荐使用。
1.2..3 双重检查
public class Person {
private static volatile Person instance;
private Person(){}
public static Person getInstance(){
if (instance == null){
synchronized (Person.class){
if (instance == null){
instance = new Person();
}
}
}
return instance;
}
}
进行两次判断,多线程进入时就可以保证线程的安全。效率也就会更高。本人推荐使用
1.3 单例模式的优点与缺点
系统内存中该类只存在一个对象,可以节省系统资源,对于一些需要频繁创建销毁的对象,使用单例模式可以提高系统性能。
这是模式创建实例是使用的相应的方法,而不是使用new关键字创建的。
以上为本人知识总结,仅供参考。