单例模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
注意:
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
优点:由于在一个系统,一个类经常被使用在不同的地方,通过单例模式,可以避免多次创建多个实例,从而节约系统资源。
懒汉模式:
//懒汉模式
public finall class Singleton{
private static Singleton instance = null;
private Singleton(){ };
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
//加锁 解决线程同步问题
public finall class Singleton{
private static Singleton instance = null;
private Singleton(){ };
public static synchorized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
//双重校验锁 解决性能问题
public finall class Singleton{
private static Singleton instance = null;
private Singleton(){ };
public static synchorized Singleton getInstance(){
if(instance == null){
synchorized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
饿汉模式
//饿汉模式 以空间换时间 一开始就创建实例
public class Singleton2 {
private static Singleton2 instance = new Singleton;//自行创建实例
private Singleton2(){ } //构造函数
public static Singleton2 getInstance(){
//通过该函数向整个系统提供实例
return instance;
}
}
饿汉模式的优点是:
可以保证多线程情况下实例的唯一性,而且getInstance直接返回唯一实例,性能非常高。
缺点:在类成员变量比较多,或变量比较大的情况下,这种模式可能会在没有使用类对象的情况下,一直占用堆内存。