单例模式之饿汉式

单例模式(饿汉式)

单例模式是一种创建性的设计模式,主要是保证一个类只能有一个实例。全局中保证一个实例的使用。

单例模式饿汉式主要的构成是如下

  • 单例类
  • 私有化构造函数(防止实例化)
  • 私有化变量
  • 公共静态获得实例的方法(在调用这个方法前就已经实例化好了)

代码

静态变量创建实例代码

package singleton;

/**
 *
 * @author: Hui
 **/
public class SingletonTest {

    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance();
        Singleton singleton1 = Singleton.getInstance();
        System.out.println(singleton == singleton1);
        System.out.println(singleton.hashCode());
        System.out.println(singleton1.hashCode());
    }

}

class Singleton{

    //1.私有化构造方法
    private Singleton(){}

    //2.创建一个静态对象
    private static Singleton instance = new Singleton();

    //3.创建一个静态返回实例方法
    public static Singleton getInstance(){
        return instance;
    }
}

静态代码块创建实例

package singleton.type2;

/**
 * @author: Hui
 **/
public class SingletonTest2 {

    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance();
        Singleton singleton1 = Singleton.getInstance();
        System.out.println(singleton == singleton1);
        System.out.println(singleton.hashCode());
        System.out.println(singleton1.hashCode());
    }

}

class Singleton {

    //1.私有化构造方法
    private Singleton() {
    }

    //2.创建一个静态对象
    private static Singleton instance;

    static {
        instance = new Singleton();
    }

    //3.创建一个静态返回实例方法
    public static Singleton getInstance() {
        return instance;
    }
}

优点:提前实例化,不存在线程并发等问题。

缺点:不符合懒加载情况,在不使用该实例的时候会造成内存浪费。

相关推荐

  1. 模式饿

    2024-07-09 18:28:05       24 阅读
  2. 饿模式

    2024-07-09 18:28:05       31 阅读
  3. 2_单列模式_饿模式

    2024-07-09 18:28:05       50 阅读
  4. 设计模式-模式饿

    2024-07-09 18:28:05       27 阅读
  5. 如何理解模式----饿

    2024-07-09 18:28:05       48 阅读
  6. C++设计模式模式饿、懒汉

    2024-07-09 18:28:05       51 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-09 18:28:05       51 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-09 18:28:05       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-09 18:28:05       44 阅读
  4. Python语言-面向对象

    2024-07-09 18:28:05       55 阅读

热门阅读

  1. WebForms SortedList 排序列表

    2024-07-09 18:28:05       24 阅读
  2. 如何编译ffmpeg支持h265(hevc)?

    2024-07-09 18:28:05       26 阅读
  3. 【AI应用探讨】—Boosting应用场景

    2024-07-09 18:28:05       21 阅读
  4. 设计模式之单例模式

    2024-07-09 18:28:05       23 阅读
  5. EXCEL VBA发邮件,实现自动化批量发送

    2024-07-09 18:28:05       23 阅读
  6. 网络“ping不通”,如何排查和解决呢?

    2024-07-09 18:28:05       22 阅读
  7. window wsl安装ubuntu

    2024-07-09 18:28:05       22 阅读
  8. 5、Redis 缓存设计相关知识点

    2024-07-09 18:28:05       26 阅读
  9. 面试题 14- I. 剪绳子

    2024-07-09 18:28:05       30 阅读
  10. 机器学习 - 比较检验

    2024-07-09 18:28:05       25 阅读