目录
单例设计模式
所谓类的单例设计模式,就是采用一定的方法保证在整个软件系统中,对某个类只能存在一个对象实例。
饿汉式和懒汉式的区别
饿汉式
好处:饿汉式线程安全
坏处:对象加载时间过长
// 饿汉式
public class SingletonTest {
public static void main(String[] args) {
Order o = Order.getinstance();
Order o1 = Order.getinstance();
System.out.println(o == o1);
}
}
class Order{
// 1.私有化类的构造器
private Order() {
}
// 2.内部创建类的对象
// 3.要求此对象也必须为静态的
private static Order instance = new Order();
// 4.提供公共的静态方法,返回类的对象
public static Order getinstance() {
return instance;
}
}
>>> true
懒汉式
好处:延迟对象的创建,提高空间效率
坏处:线程不安全
// 懒汉式
public class SingletonTest {
public static void main(String[] args) {
Order o = Order.getinstance();
Order o1 = Order.getinstance();
System.out.println(o == o1);
}
}
class Order{
// 1.私有化类的构造器
private Order() {
}
// 2.声明当前类对象,没有初始化
// 3.此对象也必须声明为static
private static Order instance = null;
// 4.声明public、static的返回当前类对象的方法
public static Order getinstance() {
if(instance == null) {
instance = new Order();
}
return instance;
}
}
>>> true