zoukankan      html  css  js  c++  java
  • 设计模式-单例模式的实现

    单例模式

    我向面试官讲解了单例模式,他对我竖起了大拇指

    面试官所认为的单例模式

    单例模式(详解,面试问题)

    image-20200722223258041

    单例模式的实现方式

    • 饿汉式
    • 懒汉式 线程不安全
    • 饿汉式 线程安全
    • 双重检查 线程安全 提高效率
    • 静态内部类
    • 枚举类

    实现代码:

    package cn.tangg;
    
    /**
     * 饿汉式
     */
    public class Singleton {
    
        private static Singleton instance = new Singleton();
    
        private Singleton() {}
    
        static Singleton getInstance() {
            return instance;
        }
    
    }
    
    
    /**
     * 懒汉式 线程不安全
     */
    class Singleton2 {
        private static Singleton2 instance;
    
        private Singleton2(){}
    
        static Singleton2 getInstance() {
            if (instance == null) {
                instance = new Singleton2();
            }
            return instance;
        }
    }
    
    /**
     * 懒汉式 线程安全
     * 加类锁
     */
    
    class Singleton3{
    
        private static Singleton3 instance;
    
        private Singleton3(){}
    
        public static synchronized Singleton3 getInstance() {
            if (instance == null) {
                instance = new Singleton3();
            }
            return instance;
        }
    }
    
    /**
     * 双重检查加锁
     */
    
    class Singleton4{
        private static volatile Singleton4 instance;
    
        private Singleton4(){}
    
        public static Singleton4 getInstance() {
            if (instance == null) {
                synchronized (Singleton4.class) {
                    if (instance == null) {
                        instance = new Singleton4();
                    }
                }
            }
            return instance;
        }
    }
    
    
    /**
     * 静态内部类
     * 静态内部类会在第一次被使用的时候被初始化,并且也只会被初始化一次,所以也包含懒加载和线程安全的特性。
     */
    
    class Singleton5{
        private Singleton5(){}
    
        public static Singleton5 getInstance() {
            return SingletonHolder.instance;
        }
    
        public static class SingletonHolder{
            public static final Singleton5 instance = new Singleton5();
        }
    }
    
    /**
     * 枚举单例
     */
    enum Singleton6 {
        INSTANCE;
        private String name = "Hello World!";
        
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    
  • 相关阅读:
    Linux文件权限
    Linux命令
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
  • 原文地址:https://www.cnblogs.com/tangg/p/13363588.html
Copyright © 2011-2022 走看看