单例选择 - 是等价的吗? [英] Singleton Alternative - is it equivalent?

查看:143
本文介绍了单例选择 - 是等价的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速问题 -



我知道标准的单例模式如下:



h3>

  public class Singleton1 
{

public static Singleton1 _Instance;
public static Singleton1 Instance
{
get
{
if(_Instance == null)
{
_Instance = new Singleton1
}
return _Instance;
}
}

private Singleton1()
{

}
}

但似乎这个代码是不必要的。对我来说,你可以用以下简单的设计模式完成同样的事情:



版本2



  public class Singleton2 
{
public static readonly Singleton2 Instance = new Singleton2();

private Singleton2()
{
}
}


b $ b

版本3



  public class Singleton3 
{
static Singleton3 $ b {
}
}

对我来说,是这样做的优越方法,因为它允许您传递参数(或不传递),但仍然有有限数量的实例。我的应用程序相当延迟/性能敏感 - 这些模式是否有性能提升?



看起来,虽然它将更长时间访问每个第一次,因为该对象正在创建。此外,原来的版本似乎有点慢,因为它必须检查每一次其他访问它的支持字段是否为null。



感谢高级!

解决方案

  public sealed class Singleton 
{
private static readonly Lazy< Singleton> lazy = new Lazy< Singleton>(()=> new Singleton());

public static Singleton实例{get {return lazy.Value; $}

b

快速,干净,线程安全。


Quick question -

I know that the standard singleton pattern is as follows:

Original

public class Singleton1
{

    public static Singleton1 _Instance;
    public static Singleton1 Instance
    {
        get
        {
            if (_Instance == null)
            {
                _Instance = new Singleton1();
            }
            return _Instance;
        }
    }

    private Singleton1()
    {

    }
}

But it seems like this code is unnecessary. To me, you could accomplish the same thing with either of the following simple design patterns:

Version 2

public class Singleton2
{
    public static readonly Singleton2 Instance = new Singleton2();

    private Singleton2()
    {
    }
}

Version 3

public class Singleton3
{
    static Singleton3()
    {
    }
}

To me, it seems like version 2 is the superior method of doing this because it allows you to pass in parameters (or not) yet still have a finite number of instance. My application is fairly latency/performance sensitive - do any of these patterns have a performance gain?

It would seem that while it will longer to access each one the first time because the object is being created. Also, it would seem that the original one is ever so slightly slower because it must check to see whether its backing field is null every time something else accesses it.

Thanks in advanced!

解决方案

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}

Fast, clean, thread-safe.

这篇关于单例选择 - 是等价的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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