A more compact way to make a singleton with a parameter

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 
        { 
            // If null then make one, else return the one we have.
            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())

. , . , .

+3
2

, , :

, , , .

, , ( )

+2

, factory ? , . singleton factory, , .

public class Singleton {

    private static final Singleton INSTANCE = new Singleton();
    private Object FactoryOutput;
    // Private constructor prevents instantiation from other classes
    private Singleton() {
    }

    public static Singleton getInstance() {
        return INSTANCE;
    }
    public Object SomeClassWhichNeedsSingleInstantiation(Object Parameter) 
    {
    If(FactoryOutput == null)
      { 
      FactoryOutput = new FactoryOutput(Parameter);
      }
    return FactoryOutput;    
    } 
}
+1

Source: https://habr.com/ru/post/1787507/


All Articles