zoukankan      html  css  js  c++  java
  • 对象创建型

    定义

    保证一个类仅有一个实例,并提供一个访问它的全局访问点
    

    使用场景

    通常使用在创建需要花费较大资源的对象上,如Hibernate中SessionFactory这样的重量级对象
    

    入门案例:

    代码:

    饿汉式:

    public class Singleton {
        private static Singleton singleton = new Singleton();
        private Singleton(){}
        public static Singleton getInstance(){
            return singleton;
        }
    }
    

    懒汉式:

    public class Singleton2 {
        private static Singleton2 singleton = null;
        private Singleton2(){}
        public static Singleton2 getInstance(){
            if(singleton == null){
                singleton = new Singleton2();
            }
            return singleton;
        }
    }
    

    懒汉式-多线程:

    public class Singleton3 {
        private static Singleton3 singleton = null;
        private Singleton3(){}
    
        //注意这是synchronized用得是类锁不是this
        public static synchronized Singleton3 getInstance(){
            if(singleton == null){
                singleton = new Singleton3();
            }
            return singleton;
        }
    }
    

    懒汉式-多线程-双重判断(高效):

    public class Singleton4 {
        private static Singleton4 singleton = null;
        private Singleton4(){}
        public static Singleton4 getInstance(){
            if(singleton == null){
                synchronized (Singleton4.class){
                    if(singleton == null){
                        singleton = new Singleton4();
                    }
                }
            }
            return singleton;
        }
    }
    
  • 相关阅读:
    Ubuntu 16.04 swoole扩展安装注意!!!
    go mod使用指南
    基于gin框架-验证码demo
    go(基于gin开发提升效率)--Air
    go mod路径引入并代码提示
    golang在win10下安装问题(一)
    win10下beego安装注意坑(一)
    API统一管理平台-YApi
    vim编辑
    swool安装(centos7)
  • 原文地址:https://www.cnblogs.com/tandi19960505/p/8285101.html
Copyright © 2011-2022 走看看