C#单身代码重用 [英] c# singleton code reuse

查看:163
本文介绍了C#单身代码重用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些类做不同的事情,但使用相同的Singleton模式从 HTTP: //www.yoda.arachsys.com/csharp/singleton.html

I have a number of classes doing different things but using the same Singleton pattern from http://www.yoda.arachsys.com/csharp/singleton.html

public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();

Singleton()
{
}

public static Singleton Instance
{
    get
    {
        lock (padlock)
        {
            if (instance==null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}
}



请问任何人有一个整洁的方式,我可以重复使用尽可能多的共同辛格尔顿码尽可能不同类之间?

Does anyone have a neat way I can reuse as much of the common Singleton code as possible between the different classes?

例如,如果我有SingletonJob1和SingletonJob2我想可以更改代码中唯一的地方,如果我移动到其他辛格尔顿模式之一。

For example if I have SingletonJob1 and SingletonJob2 I'd like to be able to change the code in only place if I move to one of the other Singleton patterns.

编辑:是的,因为人们已经从的 http://www.yoda.arachsys.com/csharp/singleton.html 是更少的代码。我看过的网页的结尾!我选择了方法2,因为单一对象涉及到的硬件设备,我想只希望他们夫妇的初始化和使用程序的任何给定的运行。方法5将初始化他们都立竿见影。

Yes as people have pointed out Method 5 from http://www.yoda.arachsys.com/csharp/singleton.html is less code. I did read to the end of the page! I chose method 2 because the Singleton objects relate to hardware devices and I want only want a couple of them initialised and used in any given run of the program. Method 5 will initialise them all straight away.

推荐答案

是否有任何理由,你正在使用的版本,而不是简单的其中一个只是初始化在声明实例?

Is there any reason you're using that version rather than the simpler one which just initializes the instance in the declaration?

public class Singleton
{
    private static Singleton instance = new Singleton();
    public static Singleton Instance { get { return instance; } }

    // Only use this if you really need it - see the page for details
    static Singleton() {}

    private Singleton()
    {
        // I assume this logic varies
    }
}

此模式是足够短,我不认为这是太大的问题,处处包含它。

This pattern is sufficiently short that I don't think it's much of a problem to include it everywhere.

我促请你考虑是否真的需要的许多单身; 。他们一般不是很大的可测性等。

I would urge you to consider whether you really need that many singletons; they're generally not great for testability etc.

编辑:如果你真的想懒惰和你使用.NET 4中,你可以用6号得到它模式是在单身页的新家

If you really, really want laziness and you're using .NET 4, you can get it with the 6th pattern which is on the singleton page's new home:

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()
    {
    }
}

这篇关于C#单身代码重用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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