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;
        }
    }
    
  • 相关阅读:
    opensuse字符和图形界面
    Eclipse编辑器小手段
    切换运行时用户以及用户组
    PHP安装和配置
    Linux程序资源限制简述
    test2234343
    找回Svn和Git不见的文件图标
    SourceInsight使用技巧
    Javascript数组使用方法
    MySQL安装和配置
  • 原文地址:https://www.cnblogs.com/tandi19960505/p/8285101.html
Copyright © 2011-2022 走看看