[SalesForce] Best way to implement a singleton class in Apex

I am trying to create a singleton class for one of my apex classes and i am running into challenges. I created some static variables to control the instances but still i am running into multiple instances as static works within the execution context.

See the static boolean variable i use to control the instance. But when i call getInstance, i always end up creating a new instance each time. Can anybody tell me what i am doing wrong and how to create a guaranteed singleton class?

public with sharing class Helper_PK_ScreenDriver {
    private static  Helper_PK_ScreenDriver instance ;
    private static  boolean isHelperInstantiated = false;
}

public static Helper_PK_ScreenDriver getInstance(String module,String entityId)
{
    System.debug('Helper pk screen driver instance'+isHelperInstantiated + 'instance' +instance);
    if(isHelperInstantiated)
    {
        return instance;
    }
    else
    {
        //This part gets executed everytime i call this from outside..
        instance = new Helper_PK_ScreenDriver(module,entityId);
        isHelperInstantiated = true;
        return instance;
    }   
}

Best Answer

If you need a static, stateful singleton, there is no such thing in Apex. That's because static in Apex does not mean the same thing as static in Java. In Apex, none of your Apex can remain in memory after a request, and none of your Apex can share memory. Static is request-scoped.

If you can provide some more detail on what you're trying to achieve, we can try to help you solve your problem; in my experience, genuinely stateful singletons are a rare requirement that almost always have some alternative.

The general solution I'd recommend that most closely resembles a stateful singleton, and allows you to pass information between requests, is some combination of an abstract utility class with static methods and persisting state via either a custom object instance or a custom setting. Locking could be an issue depending on how fancy your state needs to be.

Related Topic