首页 > 其他分享 >CSharp: Singleton Pattern in donet 6

CSharp: Singleton Pattern in donet 6

时间:2022-11-09 23:23:43浏览次数:37  
标签:donet Singleton Instance Pattern private instance static 单例 public

 

    /// <summary>
    ///单例模式 单件模式、Singleton  Pattern 
    /// </summary>
    public abstract class BaseGreeter
    {
        public virtual void Greet() =>
            Console.WriteLine($"Greetings from {GetType().Name}!");
    }


 /// <summary>
    /// 单例模式 单件模式、Singleton  Pattern 
    /// </summary>
    public class SimpleGreeter : BaseGreeter
    {
        /// <summary>
        /// 
        /// </summary>
        private static SimpleGreeter? _instance;
        /// <summary>
        /// 
        /// </summary>
        private SimpleGreeter()
        {
            Console.WriteLine("简单的单例实例化了第一次也是唯一一次!!");
        }
        /// <summary>
        /// 
        /// </summary>
        public static SimpleGreeter Instance
        {
            get
            {
                Console.WriteLine("请求简单的单例...");

                if (_instance == null)
                {
                    _instance = new SimpleGreeter();
                }

                Console.WriteLine("返回简单单例");
                return _instance;
            }
        }
    }

    /// <summary>
    /// 单例模式 单件模式、Singleton  Pattern 
    /// </summary>
    public class SimpleThreadSafetyGreeter : BaseGreeter
    {

        /// <summary>
        /// 
        /// </summary>
        private static readonly object Padlock = new();

      /// <summary>
      /// 
      /// </summary>
        private static SimpleThreadSafetyGreeter? _instance;
        /// <summary>
        /// 
        /// </summary>
        private SimpleThreadSafetyGreeter()
        {
        }
        /// <summary>
        /// 
        /// </summary>
        public static SimpleThreadSafetyGreeter Instance
        {
            get
            {
                lock (Padlock)
                {
                    if (_instance == null)
                    {
                        _instance = new SimpleThreadSafetyGreeter();
                    }

                    return _instance;
                }
            }
        }
    }


 /// <summary>
    /// 单例模式 单件模式、Singleton  Pattern 
    /// </summary>
    public class DotNetLazyGreeter : BaseGreeter
    {

        /// <summary>
        /// 
        /// </summary>
        private static readonly Lazy<DotNetLazyGreeter> Lazy = new(() => new DotNetLazyGreeter());
        /// <summary>
        /// 
        /// </summary>
        private DotNetLazyGreeter()
        {
        }
        /// <summary>
        /// 
        /// </summary>
        public static DotNetLazyGreeter Instance => Lazy.Value;
    }

  /// <summary>
    /// 单例模式 单件模式、Singleton  Pattern 
    /// </summary>
    public class DoubleCheckGreeter : BaseGreeter
    {

        /// <summary>
        /// /
        /// </summary>
        private static readonly object Padlock = new();
        /// <summary>
        /// 
        /// </summary>
        private static DoubleCheckGreeter? _instance;
        /// <summary>
        /// 
        /// </summary>
        private DoubleCheckGreeter()
        {
        }


        /// <summary>
        /// Gets instance in a way to support multi-threaded applications through 'double checked locking'
        /// pattern which (once the instance exists) avoids locking each time the method is invoked.
        /// </summary>
        [SuppressMessage("Maintainability", "CA1508:Avoid dead conditional code",
            Justification = "If the first check determines that instance is null, that might not be the case for the second check in multi-threaded scenarios.")]     
       
        public static DoubleCheckGreeter Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (Padlock)
                    {
                        if (_instance == null)
                        {
                            _instance = new DoubleCheckGreeter();
                        }
                    }
                }

                return _instance;
            }
        }
    }

 /// <summary>
    /// 单例模式 单件模式、Singleton  Pattern 
    /// </summary>
    public class LocklessFullyLazyGreeter : BaseGreeter
    {

        /// <summary>
        /// 
        /// </summary>
        private LocklessFullyLazyGreeter()
        {
        }
        /// <summary>
        /// 
        /// </summary>
        public static LocklessFullyLazyGreeter Instance => Nested.Instance;
        /// <summary>
        /// 
        /// </summary>
        private class Nested
        {
            /// <summary>
            /// Although nested classes have access to the enclosing class's private members,
            /// the reverse is not true, hence the need for instance to be internal here.
            /// </summary>
            internal static readonly LocklessFullyLazyGreeter Instance = new();

            // Explicit static constructor to tell C# compiler not to mark as BeforeFieldInit.
            // http://csharpindepth.com/Articles/General/Singleton.aspx
            static Nested()
            {
            }
        }
    }


    /// <summary>
    /// 单例模式 单件模式、Singleton  Pattern 
    /// </summary>
    public class LocklessGreeter : BaseGreeter
            {
                /// <summary>
                /// 
                /// </summary>
                private static readonly LocklessGreeter InstanceValue = new();

                // Explicit static constructor to tell C# compiler not to mark type as BeforeFieldInit.
                static LocklessGreeter()
                {
                }
                 /// <summary>
                 /// 
                 /// </summary>
                private LocklessGreeter()
                {
                }
                /// <summary>
                /// 
                /// </summary>
                public static LocklessGreeter Instance => InstanceValue;
         }
}

  

调用:

           Geovin.Du.DuSingleton.Types.SimpleGreeter.Instance.Greet();
            Geovin.Du.DuSingleton.Types.SimpleThreadSafetyGreeter.Instance.Greet();
            Geovin.Du.DuSingleton.Types.DoubleCheckGreeter.Instance.Greet();
            Geovin.Du.DuSingleton.Types.LocklessGreeter.Instance.Greet();
            Geovin.Du.DuSingleton.Types.LocklessFullyLazyGreeter.Instance.Greet();
            Geovin.Du.DuSingleton.Types.DotNetLazyGreeter.Instance.Greet();

  

输出:

2
最初的问候...

请求简单的单例...
返回简单单例
Greetings from SimpleGreeter!
Greetings from SimpleThreadSafetyGreeter!
Greetings from DoubleCheckGreeter!
Greetings from LocklessGreeter!
Greetings from LocklessFullyLazyGreeter!
Greetings from DotNetLazyGreeter!

再见的问候...

请求简单的单例...
返回简单单例
Greetings from SimpleGreeter!
Greetings from SimpleThreadSafetyGreeter!
Greetings from DoubleCheckGreeter!
Greetings from LocklessGreeter!
Greetings from LocklessFullyLazyGreeter!
Greetings from DotNetLazyGreeter!

  

 

 

 

萬事萬物並不是存在就有意義的。顯然,人、動物和物體以物的形式存在著,並且會有不同程度的改變,但是,賦予它們意義的並非單純的物質上的存在。要獲得確定的意義,就必須賦予人、動物和物體以象徵意味。只有把生命和無生命的棲居者都轉換為象徵性的實體,社會與文化才能理解這個世界—即使只是嘗試性的、暫時性的理解。人們使用的象徵符號多種多樣,其含義因社會和文化的差異而發生變化。此類象徵符號、囊括了塑造特定群體之價值體系和行為方式的詞語、視覺形象以及禮儀和習俗。人、動物和物體皆與象徵符號相關,正是在這一點上,一個群體經由教育而認識到自身的存在是意味深長或意義重大的。
同時,任何物質形式都不可能擁有一個最終或者永恆的意義。事實上,隨著它所屬的文化或社會形態的改變,其含義將不可避免地發生與變化。這種說法如果適用於具體的實體,並且會因此發生變化,這無疑已被用來意指抽象概念的詞語的變化所證實—諸如“文化”、“社會”、“價值”和“社群”等。此類觀念並沒有指向普遍性的範疇,毋寧說,它們把握住了特定語境中的意義,而意義取決於那些用來界定意義的象徵符號。
---《Critical and Cultural Theory》 by Dani Cavallaro

 

 

标签:donet,Singleton,Instance,Pattern,private,instance,static,单例,public
From: https://www.cnblogs.com/geovindu/p/16875562.html

相关文章

  • CSharp: Classes, Structures, And Records in c# 10(donet 6)
     #regionRecordTypesRecordClassinC#10///<summary>///Positionalparameterssyntax///位置参数的语法///</summary>///<pa......
  • CSharp: Abstract Factory Pattern in donet 6
     usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceGeovinu.Du.DuAbstractFactory......
  • CSharp: Factory Method Pattern in donet 6
     ///<summary>///TheProductdeclarestheinterface,whichiscommontoallobjects///thatcanbeproducedbythecreator<seecref="Restau......
  • Singleton、Scoped、Transient 的应用情景有哪些
    对于方法都是线程安全的类型,一般使用单例。对于对象依赖了处理上下文,或者使用了有限资源(如数据库连接),一般使用Scoped或者Transient。Scoped、Transient的区别是你在同一个......
  • Checkerboard Pattern Shader
    写在前面:本文章为个人学习笔记,方便以后自己复习,也希望能帮助到他人。由于本人水平有限难免出现错误,还请评论区指出,多多指教。部分图元和素材来源于网络,如有侵权请联系本......
  • 2.单例模式(Singleton)JAVA语言实现
    单例模式实现1.私有的构造方法2.私有的静态的当前类对象作为属性3.共有的静态的方法返回当前类对象单例模式实现方式有三种(指的时对象的加载)1.饿汉式(立即加载)对象启动时就......
  • Python: Flyweight Pattern
    DuFlyweight.py#享元模式FlyweightPatterngeovindu,GeovinDu,涂聚文importtimeclassArrow:def__init__(self,x,y,z,velocity):self.x=x......
  • CSharp: The single-responsibility principle (SRP) in donet core 6
    SingleResponsibilityPrincipleSOLIDDesignPatternsSOLIDisanacronymforfiveprinciplesofarchitecture.S–SingleResponsibilityPrincipleO–OpenClo......
  • Python: Command Pattern
    GeovinDuCommand.py#命令模式CommandPatternGeovinDuCommand.py#WebBrowser:classWebBrowser(object):def__init__(self):self.bookmarks=......
  • Core J2EE Patterns - Data Access Object
    Incomputersoftware,adataaccessobject(DAO)isapatternthatprovidesanabstractinterfacetosometypeofdatabaseorotherpersistencemechanism.Bymap......