zoukankan      html  css  js  c++  java
  • 设计模式之单例模式

    单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

    • 1、单例类只能有一个实例。
    • 2、单例类必须自己创建自己的唯一实例。
    • 3、单例类必须给所有其他对象提供这一实例。
    • 使用场景:

      • 1、要求生产唯一序列号。
      • 2、WEB 中的计数器,不用每次刷新都在数据库里加一次,用单例先缓存起来。
      • 3、创建的一个对象需要消耗的资源过多,比如 I/O 与数据库的连接等。  
      • 单例模式的几种实现方式:

        • 懒汉式,线程不安全

        • public class Singleton {
        • private static Singleton instance;
        • private Singleton (){}
        • public static Singleton getInstance() {
        • if (instance == null) {
        • instance = new Singleton();
        •         }
        • return instance;
        •     }
        • }
        • 懒汉式,线程安全

        • public class Singleton {
        • private static Singleton instance;
        • private Singleton (){}
        • public static synchronized Singleton getInstance() {
        • if (instance == null) {
        • instance = new Singleton();
        • }
        • return instance;
        • } }
        • 饿汉式

        • public class Singleton {
        • private static Singleton instance = new Singleton();
        • private Singleton (){}
        • public static Singleton getInstance() { return instance; } }
        • 双检锁/双重校验锁(DCL,即 double-checked locking)线程安全

        • public class Singleton {
        • private volatile static Singleton singleton;
        • private Singleton (){}
        • public static Singleton getSingleton() {
        • if (singleton == null) {
        • synchronized (Singleton.class) {
        • if (singleton == null) {
        • singleton = new Singleton();
        • } } }
        • return singleton; } }
        • 登记式/静态内部类

        • public class Singleton {
        • private static class SingletonHolder {
        • private static final Singleton INSTANCE = new Singleton();
        • }
        • private Singleton (){}
        • public static final Singleton getInstance() {
        • return SingletonHolder.INSTANCE;
        • } }
        • 枚举

        • public enum Singleton {
        • INSTANCE;
        • public void whateverMethod() { }
        • }
  • 相关阅读:
    使用svn diff的-r参数的来比较任意两个版本的差异
    mysql client常见error总结
    mysql 中 unix_timestamp,from_unixtime 时间戳函数
    hyperledger explorer 结合 fabric1.4 搭建 区块链浏览器 踩坑记录
    fabric1.4 网络操作
    通过配置连接池大小来提升性能
    docker基本操作及介绍
    InnoDB 引擎中的索引类型
    MySQL互联网业务使用建议
    mysql InnoDB引擎是否支持hash索引
  • 原文地址:https://www.cnblogs.com/liufei-90046109/p/11383335.html
Copyright © 2011-2022 走看看