目的:使得一个类只能够创建一个对象
饿汉式 vs 懒汉式
public class TestBank {
public static void main(String[] args) {
Bank bank1 = Bank.getInstance();
Bank bank2 = Bank.getInstance();
Bank bank1 = Bank.instance;
Bank bank2 = Bank.instance;
System.out.println(bank1 == bank2);
}
}
饿汉式
class Bank {
private Bank() {
}
private static Bank instance = new Bank();
public static Bank getInstance() {
return instance;
}
}
懒汉式(存在线程的安全问题的)
class Car{
private Car(){
}
private static Car car = null;
public static Car getCar(){
if(car == null){
car = new Car();
//return car;
}
return car;
}
} |
|