• 大话设计模式之单例模式


    单例模式

      一个类有且只有一个实例;

    特点

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

    单例模式的几种实现方式

    一:饿汉式

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

    饿汉式是指在类加载的过程中就完成了实例化;避免了多线程问题,因此属于线程安全;但是没有达到 lazy loading 的效果,所以可能存在内存浪费的情况。

    二:懒汉式(线程不安全)

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

     这种实现最大的问题就是不支持多线程。因为没有加锁 synchronized,线程不安全 

    三:懒汉式(线程安全)

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

     解决上述线程不安全的方法就是在方法上加个同步(synchronized),因此也导致了效率太低,所以不推荐使用。

    四:双重锁定  

    public class Singleton {
        private static volatile Singleton singleton;
        private Singleton(){}
        public static Singleton getInstance(){
            if(singleton==null){//防止重复锁定
                synchronized(Singleton.class){//Singleton.class表示锁定的是Singleton的class对象;如果是this则表示当前对象
                    if(singleton==null){ 
                        singleton = new Singleton();
                    }
                }
            }
            return singleton;
        }
    }

    这种方式采用双锁机制,安全且在多线程情况下能保持高性能;

  • 相关阅读:
    leetcode 18 4Sum
    leetcode 71 Simplify Path
    leetcode 10 Regular Expression Matching
    leetcode 30 Substring with Concatenation of All Words
    leetcode 355 Design Twitte
    leetcode LRU Cache
    leetcode 3Sum
    leetcode Letter Combinations of a Phone Number
    leetcode Remove Nth Node From End of List
    leetcode Valid Parentheses
  • 原文地址:https://www.cnblogs.com/chenpt/p/9336841.html
Copyright © 2020-2023  润新知