所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法。
饿汉式
public class SingletonTest1 {
public static void main(String[] args) {
Bank bank1 = Bank.getInstance();
Bank bank2 = Bank.getInstance();
System.out.println(bank1 == bank2);//true
}
}
class Bank {
//创建私有化构造器
private Bank() {
}
//内部提供一个当前类的实例 且为静态
private static Bank instance = new Bank();
//提供公共的静态方法,返回当前类的对象
public static Bank getInstance() {
return instance;
}
}
懒汉式
class Order {
private Order() {
}
private static Order instance = null;
public static Order getInstance() {
if (instance == null) {
instance = new Order();
} return instance;
}
}
public class SingletonTest2 {
public static void main(String[] args) {
Order order1 = Order.getInstance();
Order order2 = Order.getInstance();
System.out.println(order1 == order2);//true
}
}