[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,可以看出不同的线路访问达到了单体。

posted @ 2017-01-26 10:30  CharyGao  阅读(457)  评论(0编辑  收藏  举报