单例模式(饿汉式和懒汉式)

编程

饿汉式

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

}

}

以上是 单例模式(饿汉式和懒汉式) 的全部内容, 来源链接: utcz.com/z/512992.html

回到顶部