在为包含状态变量的类使用Singleton
或Static
之间进行选择时遇到很多麻烦。我希望类对象实例化并且只作为一个存在。
我知道两种方式都可以存储状态变量。 Static
类似乎很容易处理变量,因为所有方法都将成为static
,他们可以访问static
变量而无需进一步的工作。
但是,Singleton
的情况不同。我有两种方法;需要访问Singleton
Instance
变量的其他类型,以及无法访问Instance
变量的其他变量,我可以将其标记为静态变量。
一个例子:
/// <summary>Singleton.</summary>
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton(); /// <summary>Instance.</summary>
public static Singleton Instance { get { return instance; } }
private int integer; /// <summary>Integer.</summary>
public int Integer { set { integer = value; } get { return integer; } }
/// <summary>Constructor.</summary>
private Singleton() { }
/// <summary>TestA</summary>
public void TestA(int val)
{
Integer = val;
}
/// <summary>TestB</summary>
public static int TestB(int val)
{
return Instance.Integer * val;
}
/// <summary>TestC</summary>
public static int TestC(int val)
{
return val * val;
}
}
从上面给出的例子中,有三种方法; TestA
,TestB
和TestC
。
TestA
是一个non-static
实例方法,可以访问其属性。TestB
是static
方法,但访问Instance
以获取其属性。TestC
是实例无用的static
方法。这引出了一个问题:
Singleton
是否只包含static
方法,并通过Instance
static
属性访问其Instance
属性和方法?换句话说,所有方法都类似于TestB
或TestC
。Singleton
是否只包含non-static
种方法,无论是否需要Instance
?所有方法与TestA
类似。Singleton
是否应包含混合static
和non-static
(在这种情况下,TestA
和TestB
类)方法?我相信它会变得相当混乱。Singleton
的想法,并且对于每个仅要实例化一次的类,请使用所有static
?修改:对于类似问题,Singleton
旁边是否应包含Static
变量/字段/属性?
答案 0 :(得分:3)
你不应该混淆这两种模式。
如果你有一个Singleton模式,唯一的静态字段应该是Instance(+ getter)。您应该可以通过实例访问所有方法和字段。如果你混淆它只会引起混淆。
如果选择静态类模式,请不要在.NET中使用秘密实例。
如果您不确定哪种模式最适合您,请查看此Singleton-vs-Static文章。它解释了两者的专业人士和对象:https://www.dotnetperls.com/singleton-static