作用:确保一个类只有一个实例对象。
实现方式有:饿汉模式、懒汉模式
饿汉模式:加载类时就已经新建号对象了,这个对象就是全局唯一存在的对象,使用时只需要调用对应的方法将这个对象返回给使用者
public class Singleton {
private static Singleton singleton = new Singleton();
public static Singleton getInstance(){
return singleton;
}
}
懒汉模式:当第一次使用这个对象时,才会新建,今后使用时直接返回这个对象。
public class Singleton {
private static Singleton singleton;
public static synchronized Singleton getInstance(){
if(singleton==null){
singleton = new Singleton();
}
return singleton;
}
}
单例模式的优点:
- 在内存中只有一个对象,节省内存空间。
- 避免频繁的创建销毁对象,可以提高性能。
- 避免对共享资源的多重占用。
- 可以全局访问。
主要注意的问题:
- 获取单例对象时必须使用单例对象提供的方法获取,不能使用其他方法。
- 多线程时注意单例模式的线程安全