哪个是实现Singleton Pattern的最佳方法? [英] Which is the best way to implement Singleton Pattern ?

查看:84
本文介绍了哪个是实现Singleton Pattern的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我刚开始学习这个设计模式我对Singleton模式有点困惑,因为当我在google上搜索同样的问题时,我发现了不同的实现方式它。但我想知道哪种方法最好,这些实施方式有何不同。



1-无线程安全单例。

2-线程安全单例。

3-线程 - 使用双重检查锁定的安全单例。

4-线程安全单例不使用锁定而不进行惰性实例化。

5-完全懒惰的实例化。

6-使用.NET 4的Lazy< t>类型。





提前致谢及时回复!!

Hello guys,

I just started learning this Design Pattern I am little bit confused about Singleton pattern because when search same question on google I found different way to implement it. But I want to know which is best method what is difference in these ways of implementing.

1- No Thread Safe Singleton.
2- Thread-Safety Singleton.
3- Thread-Safety Singleton using Double-Check Locking.
4- Thread-Safe Singleton without using locks and no lazy instantiation.
5- Fully lazy instantiation.
6- Using .NET 4's Lazy<t> type.


Thanks in advance for prompt reply!!

推荐答案

正如您所问 - 我正在实施一个新的SignalR Hub和Ticker。这是我的Ticker单例(6-使用.NET 4的Lazy类型。)



As you ask - I am implementing a new SignalR Hub and Ticker. Here is my Ticker singleton (6- Using .NET 4's Lazy type.)

public class ServicesTicker
{
    // Singleton instance
    private readonly static Lazy<ServicesTicker> _instance = new Lazy<ServicesTicker>(
        () => new ServicesTicker(GlobalHost.ConnectionManager.GetHubContext<ServicesHub>().Clients));

    public static ServicesTicker Instance { get { return _instance.Value; } }

    private IHubConnectionContext<dynamic> Clients { get; set; }

    private ServicesTicker(IHubConnectionContext<dynamic> clients)
    {
        Clients = clients;
    }
}





我会将此包含在评论中,但代码部分会看起来不好



I would have included this in the comment but the code section would look bad


延迟加载的不安全方式: -

Unsafe Way with Lazy Loading :-
public class Program
    {
        public static void Main(string[] args)
        {
            //Once you call this it will check if _instance is not null and call the constructor if null else return the existing one.
            var singletonInstance1 = Task.Run<Singleton>(() => Singleton.Intance());

            //If we try to execute two lines one by one of different thread, which causes to a unsafe call to _instance. Because two different task can go inside the Intance() function and call the constructor twice. Although _instance is static and initialize only once but can raise two calls.
            var singletonInstance2 = Task.Run<Singleton>(() => Singleton.Intance());
        }
    }

    public class Singleton
    {
        //It should has Private / Protected constructor, so can not be called from outside of class.
        private Singleton()
        { }

        //Static field to hold instance of singleton class. This will be initialized on demand.
        private static Singleton _instance;
        public static Singleton Intance()
        {
            if (_instance == null)
                return new Singleton();
            else
                return _instance;
        }
    }







预先加载线程安全方式: - < br $>





Thread Safe ways with Eager Loading :-

public class Singleton
   {
       //It should has Private / Protected constructor, so can not be called from outside of class.
       private Singleton()
       { }

       //Now we called the constructor before executing the Instance() method. So _instance can not be null in this case.
       private static Singleton _instance = new Singleton();
       public static Singleton Intance()
       {
           //No Need to check _instance is null or not, because it will always available.
           return _instance;
       }
   }







使用延迟加载的线程安全: -






Thread safe with Lazy loading :-

public class Singleton
    {
        //It should has Private / Protected constructor, so can not be called from outside of class.
        private Singleton()
        { }

        //Static field to hold instance of singleton class. This will be initialized on demand.
        private static Singleton _instance;
        public static Singleton Intance()
        {
            //use lock to create a thread safe call to _instance variable. Here before checking _instance variable we locked that object so no other thread can use it until free.
            lock (_instance) ;
            if (_instance == null)
                return new Singleton();
            else
                return _instance;
            
        }
    }


这篇关于哪个是实现Singleton Pattern的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆