English 中文(简体)
C#[闭门]单一吨位模式
原标题:Singleton Pattern for C# [closed]
  • 时间:2010-04-19 11:42:32
  •  标签:
  • c#
  • singleton
Closed. This question is opinion-based. It is not currently accepting answers.

我需要储存一系列需要在全球获得的变量,我很想知道单一州模式是否适用。 从我所看到的例子来看,单一州模式只是一个可以继承的静态类别。 但我所看到的例子对我的需求来说过于复杂。 最简单的单一州类别是什么? 难道我只是一个静态、密封的类别,其中有一些变量?

最佳回答
问题回答

有几个模式可能适合你,一个单一州是更糟糕的。

<>Registry

struct Data {
  public String ProgramName;
  public String Parameters;
}

class FooRegistry {
  private static Dictionary<String, Data> registry = new Dictionary<String, Data>();
  public static void Register(String key, Data data) {
     FooRegistry.registry[key] = data;
  }
  public static void Get(String key) {
     // Omitted: Check if key exists
     return FooRegistry.registry[key];
  }
}

Advantages

  • Easy to switch to a Mock Object for automated testing
  • You can still store multiple instances but if necessary you have only one instance.

Disadvantages

  • Slightly slower than a Singleton or a global Variable

<>Static Level

class GlobalStuff {
  public static String ProgramName {get;set;}
  public static String Parameters {get;set;}
  private GlobalStuff() {}
}

Advantages

  • Simple
  • Fast

Disadvantages

  • Hard to switch dynamically to i.e. a Mock Object
  • Hard to switch to another object type if requirements change

<>光度>

class DataSingleton {
  private static DataSingleton instance = null;
  private DataSingleton() {}
  public static DataSingleton Instance {
     get {
         if (DataSingleton.instance == null) DataSingleton.instance = new DataSingleton();
         return DataSingleton;
     }
  }
}

Advantages

  • None really

Disadvantages

  • Hard to create a threadsafe singleton, the above Version will fail if multiple threads access the instance.
  • Hard to switch for a mock object

我个人喜欢书记官处模式,但YMMV。

你们应当研究依赖性注射,因为它通常被认为是最佳做法,但太大了在这里解释的话题:

http://en.wikipedia.org/wiki/Dependency_Injection”rel=“nofollow noreferer”>Dependency Injection

单一州只剩下可以继承的固定等级。 它是一个正常的班级,只能一度进行即时处理,人人都可以分享这一单一案例(使它变得安全得多)。

独一州典型的网络代码像如下。 这是一个快速的例子,并非通过任何手段执行最佳或可读安全守则:

public sealed class Singleton
{
    Singleton _instance = null;

    public Singleton Instance
    {
        get
        {
            if(_instance == null)
                _instance = new Singleton();

            return _instance;
        }
    }

    // Default private constructor so only we can instanctiate
    private Singleton() { }

    // Default private static constructor
    private static Singleton() { }
}

如果你重新走下你重新思考的道路,一个静态的密封的班子将只做罚款。

采用C第6号自动-财产启动器。

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

简明扼要——我很乐于听下台。

我知道这个问题是老的,但这里是另一个使用4.Net(包括网络核心和网络标准)的解决办法。

第一,界定你们的等级,将变成一个单一州:

public class ClassThatWillBeASingleton
{
    private ClassThatWillBeASingleton()
    {
        Thread.Sleep(20);
        guid = Guid.NewGuid();
        Thread.Sleep(20);
    }

    public Guid guid { get; set; }
}

在“第一”类例中,对一名睡觉的建筑商进行了定义,然后制作一部新的指南,将其公有财产排除在外。 (睡仅作一致测试)

通知说,施工者是私人的,因此没有人能够提出这一类别的新案例。

现在, 我们需要确定将这一类变为单一吨的包装:

public abstract class SingletonBase<T> where T : class
{
    private static readonly Lazy<T> _Lazy = new Lazy<T>(() =>
    {
        // Get non-public constructors for T.
        var ctors = typeof(T).GetConstructors(System.Reflection.BindingFlags.Instance |
                                              System.Reflection.BindingFlags.NonPublic);
        if (!Array.Exists(ctors, (ci) => ci.GetParameters().Length == 0))
            throw new InvalidOperationException("Non-public ctor() was not found.");
        var ctor = Array.Find(ctors, (ci) => ci.GetParameters().Length == 0);
        // Invoke constructor and return resulting object.
        return ctor.Invoke(new object[] { }) as T;
    }, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);

    public static T Instance
    {
        get { return _Lazy.Value; }
    }
}

通知说,它使用拉齐创建“外地代码”——Lazy,该编码知道如何用它作为私人建筑商对某类进行即时处理。

并且界定了一条“财产编码”,以获取拉齐油田的价值。

通知<代码>LazyThreadSafetyMode 输往拉齐的建筑商。 正在使用<代码>ExecutionAndPublication。 因此,只有一条路子才能开始拉齐地区的价值。

现在,我们必须做的是确定一个单一州:

public class ExampleSingleton : SingletonBase<ClassThatWillBeASingleton>
{
    private ExampleSingleton () { }
}

这里是使用的一个例子:

ExampleSingleton.Instance.guid;

还有一个检验标准,就是说两条镜子会得到单一州同样的检查:

[Fact()]
public void Instance_ParallelGuid_ExpectedReturnSameGuid()
{
    Guid firstGuid = Guid.Empty;
    Guid secondGuid = Guid.NewGuid();

    Parallel.Invoke(() =>
    {
        firstGuid = Singleton4Tests.Instance.guid;
    }, () =>
    {
        secondGuid = Singleton4Tests.Instance.guid;
    });

    Assert.Equal(firstGuid, secondGuid);
}

这一检验标准同时称为拉齐地区的价值,我们要说,从这一财产(Lazy的Value)中归还的两种情况相同。

关于这一主题的更多详情,见:http://csharpin deep.com/Articles/General/Singleton.aspx”rel=“nofollow noreferer”>。 C# in Depth

Use your language features. Mostly simple thread-safe implementation is:

public sealed class Singleton
{
    private static readonly Singleton _instance;

    private Singleton() { }

    static Singleton()
    {
        _instance = new Singleton();
    }

    public static Singleton Instance
    {
        get { return _instance; }
    }
}

...what would be the very simplest singleton class?

还有一种可能的解决办法。 我认为,最简单、最直截了当、最容易使用的方法就是这样:

//The abstract singleton
public abstract class Singleton<T> where T : class
{
    private static readonly Lazy<T> instance = new Lazy<T>( CreateInstance, true );

    public static T Instance => instance.Value;

    private static T CreateInstance()
    {
        return (T)Activator.CreateInstance( typeof(T), true);
    }
}

//This is the usage for any class, that should be a singleton
public class MyClass : Singleton<MyClass>
{
    private MyClass()
    {
        //Code...
    }

    //Code...
}

//Example usage of the Singleton
class Program
{
    static void Main(string[] args)
    {
        MyClass clazz = MyClass.Instance;
    }
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签