单例模式

单例模式 :保证一个类只有一个实例的实现方法。 可以认为就是一个全局变量

使用场景

我们在浏览BBS、SNS网站的时候,常常会看到“当前在线人数”这样的一项内容。对于这样的一项功能,我们通常的做法是把当前的在线人数存放到一个内存、文件或者数据库中,每次用户登录的时候,就会马上从内存、文件或者数据库中取出,在其基础上加1后,作为当前的在线人数进行显示,然后再把它保存回内存、文件或者数据库里,这样后续登录的用户看到的就是更新后的当前在线人数;同样的道理,当用户退出后,当前在线人数进行减1的工作。所以,对于这样的一个需求,我们按照面向对象的设计思想,可以把它抽象为“在线计数器”这样一个对象。

单例模式能够保证一个类仅有唯一的实例,并提供一个全局访问点。

优点

在内存中只有一个对象,节省内存空间;

避免频繁的创建销毁对象,可以提高性能;

避免对共享资源的多重占用,简化访问;

为整个系统提供一个全局访问点。

代码实现如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Singleton.GetThreadSafeSingleton().Add("121");
            Singleton.GetThreadSafeSingleton().Add("122");
            var a = Singleton.GetThreadSafeSingleton().ReturnValue();
        }
    }
}

懒汉模式---线程不安全

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPattern
{
    /// <summary>
    /// 单例模式(懒汉模式)--线程不安全
    /// </summary>
    public class Singleton
    {
        private static Singleton singleton = new Singleton();
        private static List<string> list = new List<string>();

        private Singleton()
        {
           
        }

        /// <summary>
        /// 获取实例
        /// </summary>
        /// <returns></returns>
        public static Singleton GetThreadSafeSingleton()
        {           
            return singleton;
        }

        public void Add(string value)
        {
            list.Add(value);
        }

        public List<string> ReturnValue()
        {
           return  list;
        }
    }
}

恶汉模式--线程安全

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPattern
{
    /// <summary>
    /// 单例模式(恶汉模式)---线程安全
    /// </summary>
    public class Singleton
    {
        private static object obj = new object();

        private static Singleton singleton;
        private static List<string> list = new List<string>();

        private Singleton()
        {
           
        }

        /// <summary>
        /// 获取实例-线程安全
        /// </summary>
        /// <returns></returns>
        public static Singleton GetThreadSafeSingleton()
        {
            if (singleton == null)
            {
                lock (obj)
                {
                    singleton = new Singleton();
                }
            }
            return singleton;
        }

        public void Add(string value)
        {
            list.Add(value);
        }

        public List<string> ReturnValue()
        {
           return  list;
        }
    }
}
原文地址:https://www.cnblogs.com/macT/p/11803455.html