-
对某个类只能存在一个对象实例
①构造器的访问权限设置为private
②调用该类的某个静态方法
③该类对象的变量也必须定义成静态的 -
区分饿汉式和懒汉式
饿汉式:坏处:对象加载时间过长 好处:饿汉式是线程安全的
懒汉式:好处:延迟对象的创建 目前写法的坏处:线程不安全
package com.atguigu.java;
public class Test { //饿汉式
public static void main(String[] args) {
Bank bank1 = Bank.getInstance();
System.out.println(bank1);
}
}
class Bank {
private Bank() {
}
private static Bank instance = new Bank();
public static Bank getInstance() {
return instance;
}
}
package com.atguigu.java;
public class Test1 { //饱汉式
public static void main(String[] args) {
Order order1 = Order.getInstance();
System.out.println(order1);
}
}
class Order{
private Order() {
}
private static Order instance = null;
public static Order getInstance() {
if(instance == null) {
instance = new Order();
return instance;
}
return instance;
}
}
网友评论