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

    概念:

      单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。

      通过单例模式可以保证系统中一个类只有一个实例。

      可以分为懒汉模式、饿汉模式。

    特点:

    1. 私有的构造函数,防止从外部构造对象。
    2. 静态的私有变量存储对象。
    3. 共开的获取对象的方法。

    好处:

      通过运用单例模式,我们可以避免重复构造对象,从而节省系统的内存资源消耗。

    代码:

      网上有人总结有7种写法,有兴趣的可以写写看,查查看。这里说几个有特点的

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

    public class Singleton {
        private Singleton(){
        }
        //饿汉模式
        private static final Singleton instance = new Singleton();
        public static Singleton getInstance(){
            return instance;
        }
    }

    public class Singleton {
        private Singleton(){
        }
        //双重校验锁
        private volatile static Singleton instance = null;
        public static Singleton getInstance(){
            if(instance==null){
                synchronized(Singleton.class){
                    if(instance == null){
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }

    public enum SingletonEnum {
        //枚举
        instance;
        private SingletonEnum(){
        }
    }

      还有//静态块,//内部类实现的,本质还是懒汉、饿汉的变体!

  • 相关阅读:
    Sample Page
    3.21之前刷题总结
    存储过程动态组建查询where语句
    SQL常备知识
    学习SilverLight:(1)SilverLight3.0和JavaScript交互
    SQL SERVER 2005 Tempdb
    学习atlas
    sql server系统表详细说明(转)
    js 基数排序的过程
    vuerouter 刷新页面后 url地址不变 参数还在 保留当前页 routerlink取值 this.$route
  • 原文地址:https://www.cnblogs.com/start-fxw/p/9444566.html
Copyright © 2011-2022 走看看