zoukankan      html  css  js  c++  java
  • 研磨设计模式学习笔记4单例模式Signleton

    大纲:

    1. 5种常见单例模式

    一、5种常见单例模式

    1.1饿汉式

    最简单是单例实现

    public class Singleton
    {
        private Singleton (){
            //加载配置文件....
        }
        private static Singleton singleton = new Singleton();
        public static Singleton getInstance(){
            return singleton;
        }
    }

    1.2懒汉式

    懒汉比恶汉多了懒加载的思想

    public class Singleton
    {
        private Singleton (){
            //加载配置文件....
        }
        private static Singleton singleton = null;
        public static Singleton getInstance(){
            if(singleton==null){
                singleton = new Singleton();
            }
            return singleton;
        }
    }

    1.3双检锁(DCL单例)

    上面懒汉式存在线程安全问题,可以利用双重检查加锁避免。

    public class Singleton
    {
        private Singleton (){
            //加载配置文件....
        }
        private volatile static Singleton singleton = null;
        public static Singleton getInstance(){
            if(singleton==null){
                synchronized (Singleton.class){
                    if(singleton==null){
                        singleton = new Singleton();
                    }
                }
            }
            return singleton;
        }
    }

    1.4静态内部类

    DCL这种方式解决了线程安全为题,但用了volatile,效率降低,用静态内部类可以解决这一问题。

    public class Singleton
    {
        private Singleton (){
            //加载配置文件....
        }
        private static class SingletonHolder{
            private static Singleton singleton = new Singleton();
        }
        public static Singleton getInstance(){
            return SingletonHolder.singleton;
        }
    }

    1.5枚举

    effective java推荐的一种单例模式

    public enum  Singleton
    {
        instance;
        Singleton(){
            //加载配置文件....
        }
    }
  • 相关阅读:
    事件对象阻止默认行为
    事件对象的属性和方法
    [MySQL] 中 Schema和Database的区别
    MyBatis-session-SqlSession
    Setting the Java Class Path
    MySQL Connector/J
    Backup and Recovery Types
    The MySQL Server
    Server SQL Modes
    MySQL Server and Server-Startup Programs
  • 原文地址:https://www.cnblogs.com/liuboyuan/p/9651298.html
Copyright © 2011-2022 走看看