Singleton模式的C# [英] Singleton Pattern for C#
问题描述
我需要存储一堆需要进行全局访问,我想知道,如果一个单例模式将适用变量。从我所看到的例子,一个单件模式就是这样不能被继承静态类。但我见过的例子是适合我的需要过于复杂。这将是非常简单的单身类?我不能只是做一个静态的,密封类里面一些变量?
I need to store a bunch of variables that need to be accessed globally and I'm wondering if a singleton pattern would be applicable. From the examples I've seen, a singleton pattern is just a static class that can't be inherited. But the examples I've seen are overly complex for my needs. What would be the very simplest singleton class? Couldn't I just make a static, sealed class with some variables inside?
推荐答案
通常一个单身的不是的静态类 - 单身会给你一个单一的实例的一类。
Typically a singleton isn't a static class - a singleton will give you a single instance of a class.
我不知道你的例子已经看到,但通常单件模式可以在C#中非常简单:
I don't know what examples you've seen, but usually the singleton pattern can be really simple in C#:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
static Singleton() {} // Make sure it's truly lazy
private Singleton() {} // Prevent instantiation outside
public static Singleton Instance { get { return instance; }
}
这并不困难。
单身过静态成员的优点是类可以实现接口等。有时这是有用的 - 但其他时候,静态成员确实会做的一样好。此外,它通常是以后更容易从一个单身移动到非单,例如通过在单作为配置对象的依赖类,而不是那些依赖类进行直接的静态调用。
The advantage of a singleton over static members is that the class can implement interfaces etc. Sometimes that's useful - but other times, static members would indeed do just as well. Additionally, it's usually easier to move from a singleton to a non-singleton later, e.g. passing in the singleton as a "configuration" object to dependency classes, rather than those dependency classes making direct static calls.
我个人会尽量避免使用单身尽可能 - 他们使测试更加努力,二话不说。他们可以偶尔是有用的,但。
Personally I'd try to avoid using singletons where possible - they make testing harder, apart from anything else. They can occasionally be useful though.
这篇关于Singleton模式的C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!