美文网首页
C# 单例的实现

C# 单例的实现

作者: 游戏创作者 | 来源:发表于2020-10-16 18:54 被阅读0次

    1. 静态单例

    using System;
    using System.Collections.Generic;
    
    namespace InstanceTest
    {
        public class DogManager {
            public static readonly DogManager Instance = new DogManager();
    
            private DogManager() { }
    
            public void Eat() {
                Console.WriteLine("吃");
            }
        }
         
        class Program
        {
            static void Main(string[] args)
            {
                DogManager.Instance.Eat();
            }
        }
    }
    

    2.延时单例

    using System;
    using System.Collections.Generic;
    
    namespace InstanceTest
    {
        public class DogManager {
            private static DogManager _instance = null;
    
            private DogManager() { }
    
            public static DogManager Insance() {
                if (_instance == null) {
                    _instance = new DogManager();
                }
                return _instance;
            }
    
            public void Eat() {
                Console.WriteLine("吃");
            }
        }
         
        class Program
        {
            static void Main(string[] args)
            {
                DogManager.Insance().Eat();
            }
        }
    }
    

    注意把构造函数写成private,让他不能通过new获得。

    相关文章

      网友评论

          本文标题:C# 单例的实现

          本文链接:https://www.haomeiwen.com/subject/cshtmktx.html