I am not very good at templates. (But I really understand that they are very important.) I have a script that needs a singlet, but also needs to accept a parameter. Usually for singleton, I just create a static method that does:
return _instance ?? (_instance = new SingletonClass());
But when a parameter is used, you need to pass a parameter each time to access things (just in case you are going to do the construction) or do something like this:
public class PublicFacingSingleton
{
private readonly string _paramForSingleton;
public PublicFacingSingleton(string paramForSingleton)
{
_paramForSingleton = paramForSingleton;
}
private PrivateFacingSingleton _access;
public PrivateFacingSingleton Access
{
get
{
return _access ??
(_access = new PrivateFacingSingleton(_paramForSingleton));
}
}
}
public class PrivateFacingSingleton
{
private readonly ClassWithOnlyOneInstance _singleInstance;
public PrivateFacingSingleton(string paramForSingleton)
{
_singleInstance = new ClassWithOnlyOneInstance(paramForSingleton);
}
public WorkItem ActualMethodToDoWork()
{
return _singleInstance.UseTheClass();
}
}
and then create PublicFacingSigletonand use this. For instance:
var publicFacingSingleton = new PublicFacingSingleton("MyParameter")
publicFacingSingleton.Access.ActualMethodToDoWork();
There are several problems with this. Some of them:
- I have two classes instead of one
- An obscure developer could still easily instantiate
PrivateFacingSingleton.
, , , , ActualMethodToDoWork() (.. publicFacingSingleton.Access("MyParameter").ActualMethodToDoWork())
. , . , .