zoukankan      html  css  js  c++  java
  • [No0000B3].NET C# 单体模式(Singleton)

    单体模式(Singleton)是经常为了保证应用程序操作某一全局对象,让其保持一致而产生的对象,例如对文件的读写操作的锁定,数据库操作的时候的事务回滚,
    还有任务管理器操作,都是一单体模式读取的。创建一个单体模式类,必须符合三个条件:
    1:私有构造函数(防止其他对象创建实例);
    2:一个单体类型的私有变量;
    3:静态全局获取接口

    下面我写一个类,为了看是不是单体,就加了一个计数器,如果是同一个类,那么这个类的计数每次调用以后就应该自动加一,而不是重新建对象归零:

    using System;
    using System.Threading;
    
    namespace Singleton
    {
        public class Singleton
        {
            private int _objCount;
    
            private Singleton()
            {
                Console.WriteLine("创建对象");
            }
    
            private static Singleton _objInstance;
    
            public static Singleton GetInstance()
            {
                return _objInstance ?? (_objInstance = new Singleton());
            }
    
            public void ShowCount()
            {
                _objCount++;
                Console.WriteLine($"单个对象被调用了{_objCount}次");
            }
        };
    
        public class ConsoleTest
        {
            public static void Main(string[] args)
            {
                Console.WriteLine("开始执行单体模式");
                for (int i = 0; i < 5; i++)
                {
                    Singleton.GetInstance().ShowCount();
                }
    
                for (int i = 0; i < 10; i++)
                {
                    ApartmentTest.RunMoreThread();
                }
                Console.ReadLine();
            }
        };
    
        class ApartmentTest
        {
            public static void RunMoreThread()
            {
                Thread newThread = new Thread(new ThreadStart(ThreadSingleMethod));
                newThread.SetApartmentState(ApartmentState.MTA);
                Console.WriteLine($"ThreadState:{newThread.ThreadState},ApartmentState:{newThread.GetApartmentState()},ManagedThreadId:{newThread.ManagedThreadId}");
                newThread.Start();
            }
    
            public static void ThreadSingleMethod()
            {
                Singleton.GetInstance().ShowCount();
            }
        };

    在这里可以看出,无论多线程还是单线程,每次都是使用的同一个对象,实现了单体。

    多线程中,根据ManagedThreadId,可以看出不同的线路访问达到了单体。

  • 相关阅读:
    Design Pattern Quick Overview
    [转载]最好的HTML 5编码教程和参考手册分享 .
    业务学习
    [收藏转载]明星软件工程师的十种特质
    一般函数指针和类的成员函数指针
    [LoadRunner]负载测试工具
    [收藏转载]2011 APP年终总结——日均160元的收入经历
    Importance of Side Projects
    [P4 password]Avoiding the Perforce Prompt for Password in Windows
    [收藏转载]我所积累的20条编程经验
  • 原文地址:https://www.cnblogs.com/Chary/p/No0000B3.html
Copyright © 2011-2022 走看看