• Singleton 模式的Java和C#的实现方法


    看到MSDN对Singleton模式的讲解。对其中的各种实现的代码摘录出来备用。

    Singleton 模型非常简单直观。 (通常)只有一个 Singleton 实例。 客户端通过一个已知的访问点来访问 Singleton 实例。 在这种情况下,客户端是一个需要访问唯一 Singleton 实例的对象。
    GoF Singleton 实现:
    // Declaration
    class Singleton {
    public:
        static Singleton* Instance();
    protected:
        Singleton();
    private:
        static Singleton* _instance;
    }

    // Implementation
    Singleton* Singleton::_instance = 0;

    Singleton* Singleton::Instance() {
        if (_instance == 0) {
            _instance = new Singleton;
        }
        return _instance;
    }
    使用 Java 语法的双重检验锁定 Singleton 代码(为了解决多线程应用程序)
    // C++ port to Java
    class Singleton
    {
        public static Singleton Instance() {
            if (_instance == null) {
                synchronized (Class.forName("Singleton")) {
                    if (_instance == null) {
                        _instance = new Singleton();
                    }
                 }
            }
            return _instance;     
        }
        protected Singleton() {}
        private static Singleton _instance = null;
    }

    以 C# 编码的双重检验锁定
    // Port to C#
    class Singleton
    {
        public static Singleton Instance() {
            if (_instance == null) {
                lock (typeof(Singleton)) {
                    if (_instance == null) {
                        _instance = new Singleton();
                    }
                }
            }
            return _instance;     
        }
        protected Singleton() {}
        private static volatile Singleton _instance = null;
    }
    .NET Singleton 示例(使用.net框架来解决各种问题)
    // .NET Singleton
    sealed class Singleton
    {
        private Singleton() {}
        public static readonly Singleton Instance = new Singleton();
    }

    示例 Singleton 使用
    sealed class SingletonCounter {
        public static readonly SingletonCounter Instance =
             new SingletonCounter();
        private long Count = 0;
        private SingletonCounter() {}
        public long NextValue() {
            return ++Count;
        }
    }

    class SingletonClient {
        [STAThread]
        static void Main() {
            for (int i=0; i<20; i++) {
                Console.WriteLine("Next singleton value: {0}",
                    SingletonCounter.Instance.NextValue());
            }
        }
    }

    参考:
    http://www.microsoft.com/china/MSDN/library/enterprisedevelopment/builddistapp/Exploring+the+Singleton+Design+Pattern.mspx

  • 相关阅读:
    Vue浏览器调试工具VueTools安装以及使用
    克莱姆法则 学习
    IfcFacetedBrep —Example Basin faceted brep
    行列式学习
    matlab矩阵旋转任意角度的函数 imrotate
    matlab双杆系统的支撑反力 学习
    matlab矩阵运算——乘法、除法学习
    matlab求航线图问题 学习
    matlab范德蒙矩阵生成学习
    matlab特殊矩阵生成学习
  • 原文地址:https://www.cnblogs.com/echo/p/140416.html
Copyright © 2020-2023  润新知