【发布时间】:2017-02-10 12:46:52
【问题描述】:
对于包含状态变量的类,我在选择使用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方法,并通过staticInstance属性访问其Instance属性和方法?换句话说,所有方法都类似于TestB或TestC。 - 无论是否需要
Instance,Singleton是否应该只包含non-static方法?所有方法类似于TestA。 -
Singleton是否应该同时包含static和non-static(在本例中为TestA和TestB种类)方法?我相信它会变得相当混乱。 - 如果没有,我该怎么办?我是否应该放弃
Singleton的想法,并为每个只实例化一次的类使用所有static?
编辑:有类似的问题,Singleton 是否应该在Instance 旁边包含任何Static 变量/字段/属性?
【问题讨论】:
标签: c# methods static singleton non-static