zoukankan      html  css  js  c++  java
  • (Design Pattern) Singleton.

    Role:

    The purpose of the Singleton pattern is to ensure that there is only one instance of a class, and that there is a global access point to that object.

    Design:

    • Make the constructor private and add a private static constructor as well.
    • Add a private static read-only object that is internally instantialed using the private constructor.
    • Add a public static property that accesses the private object.

    Implementation:

        public sealed class Singleton
        {
            // Private constructor.
            private Singleton()
            {
                Console.WriteLine("One instance is created."); 
            }
    
            // private object instantiated with private constructor.
            private static readonly Singleton instance = new Singleton(); 
    
            // Public static property to get the object.
            public static Singleton UniqueInstance
            {
                get
                {
                    return instance; 
                }
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                Singleton s0 = Singleton.UniqueInstance;
                Singleton s1 = Singleton.UniqueInstance;
                Singleton s2 = Singleton.UniqueInstance; 
            }
        }
  • 相关阅读:
    linux中read用法
    apt-get 使用指南
    linux文件系统
    KMP
    在C#中的各种应用
    A*算法,遗传算法
    Dijkstra算法,Floyd算法
    AE开发tips
    TOC 右键菜单
    ubuntu下的一些意外
  • 原文地址:https://www.cnblogs.com/fdyang/p/4900789.html
Copyright © 2011-2022 走看看