I am having a lot of trouble choosing between using Singleton
or Static
for a class that contains state variables. I wanted the class object to instantiate and exist only as one.
I know both ways can store state variables. Static
Class seems easy to deal with the variables as all methods will become static
, which they can access the static
variables without any further work.
However, this case is different for a Singleton
. I have both kinds of methods; A kind that needs to access to the Singleton
's Instance
variable, and other that without any access to the Instance
variable, which I can mark it static.
An Example:
/// <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;
}
}
From the example given above, there are three methods; TestA
, TestB
, and TestC
.
TestA
is anon-static
instance method that has access to its property.TestB
is astatic
method, but accesses theInstance
to get its properties.TestC
is astatic
method that the instance has no use.
This begs the question:
- Should the
Singleton
contains onlystatic
methods, and access to itsInstance
properties and methods by going through thestatic
Instance
property? In other words, all methods are similar toTestB
orTestC
. - Should the
Singleton
contains onlynon-static
methods, regardless whether if it needs theInstance
or not? All methods similar toTestA
. - Should the
Singleton
contains both mixedstatic
andnon-static
(in this case,TestA
, andTestB
kind) methods? Which I believe it can get rather messy. - If not, what should I do? Should I dump the idea of
Singleton
, and go with allstatic
for every classes that is to be instantiated only once?
Edit: With similar question, should Singleton
even contain any Static
variables/field/properties beside the Instance
?