单例模式 (饱汉式和饿汉式)
饱汉式的特点是提前在构造器里new好了,随时可以调用,省时间;
饿汉式的特点是现用现new,省运行空间
public class Singleton {
//饱汉模式
//步骤
//1. 将构造器私有化
//2. 在类的内部直接创建对象
//3. 提供一个公共的static方法,返回singleton对象
private static Singleton singleton = new Singleton();
private Singleton() {}
public Singleton getInstance(){
return singleton;
}
//饿汉模式
private static Singleton singleton = null;
private Singleton() { }
public synchronized Singleton getInstance(){
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
什么是单例模式?
所谓的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象的方法.
饱汉式VS饿汉式
1.二者的主要区别在于创建对象的时机不同:饱汉式是在加载类时就创建了对象实例,而饿汉式是在使用是才创建
2. 饱汉式不存在线程的安全问题,饿汉式存在线程的安全问题,但是可以用线程锁(synchronized )解决
3. 饱汉式可能存在浪费资源的可能,因为如果程序员一个对象实例都没使用,那么饱汉式创建的对象就浪费了,饿汉式是使用时才创建,不存在这个问题
4. javaSE的标准类中,java.lang.Runtime就是经典的单例模式