zoukankan      html  css  js  c++  java
  • 设计模式随笔(四):单例模式

    单例模式一般分为:懒汉、饿汉、双重校验锁、枚举、静态内部类五种。

    懒汉:

    第一次调用时,创建对象

    public class Single {
    
        private static Single instance;
    
        private Single(){};
    
        public static Single getInstance() {
            if (instance == null) {
                instance = new Single();
            }
            return instance;
        }
    }

    饿汉:

    public class Single {
    
        private static Single instance = new Single();
    
        private Single(){};
    
        public static Single getInstance() {
            return instance ;
        }
    }

    双重校验锁:

    public class Single {
    
        private volatile static Single singleton;  //1:volatile修饰
    
        private Single(){}
    
        public static Single getSingleton() {
            if (singleton == null) {
                synchronized (Single.class) {
                    if (singleton == null) {
                        singleton = new Single();
                    }
                }
            }
            return singleton;
        }
    
    }

    静态内部类:

    public class Single {
    
        private Single() {}
        public static Single getInstance() {
            return Inner.instance;
        }
    
        public static class Inner {
            private static final Single instance = new Single();
        }
    }

    枚举:

    public enum Singleton {  
        INSTANCE;  
        public void whateverMethod() {  
        }  
    }  
  • 相关阅读:
    Md5
    hdu 2569 彼岸
    调用系统相机相冊
    白盒測试
    HDU 1501
    IOS常见错误分析解决(一直更新) 你值得收藏-综合贴
    读“程序猿生存定律”笔记
    Halcon导出的cpp, VC++环境配置
    POJ 1260 Pearls (动规)
    hdoj-1856-More is better【并查集】
  • 原文地址:https://www.cnblogs.com/chylcblog/p/13253215.html
Copyright © 2011-2022 走看看