单例模式的实现

137 阅读1分钟

创建单例模式

  1. 私有构造器
  2. 创建内部静态成员属性
  3. 创建公共静态方法

饿汉式

public class Bank {
    //1、构造器私有化
    private Bank() {
    }

    //2、内部创建类的对象
    private static Bank instance = new Bank();

    //3、提供公共的方法,返回类的对象
    public static Bank getInstance() {
        return instance;
    }
}

懒汉式

public class Order {

    //1、私有构造器
    private Order() {
    }

    //2、声明当前类对象,没有初始化
    private static Order instance = null;

    //3、声明公共方法
    public static Order getInstance() {
        if (instance == null){
            instance = new Order();
        }
        return instance;
    }
}

饿汉式和懒汉式的使用

饿汉式

  • 好处:是线程安全的
  • 坏处:对象加载时间过长

懒汉式

  • 好处:延迟对象的创建
  • 坏处:线程不安全