In a recent post, someone asked about implementing the Singleton Pattern in Apex, and I offered this link as a resource, and there was also this session at DF 11 that talked about the Singleton pattern. @kraybill suggested that a stateful singleton in Apex didn’t really exist/make sense, but that made me wonder whether using it for a non-stateful purpose is also an overkill. The DF 11 session explains how you could use it for as a RecordType Lookup Cache Utility to avoid multiple describes – and I have such a need for a trigger handler class I am building. But I know I could also just add a couple of static map variables to a class, and a getter that populates the map if it is null, which would achieve the same thing. So are there are pros-cons to either approach? If the Singleton pattern is not appropriate here, is there a time when it is? Any insights appreciated!
Singletons not only are not needed in Apex, they are basically pointless. In that previous thread, I described why stateful singletons are pointless, but stateless singletons are pretty much in the same boat, simply because the instantiation/cache step is unnecessary.
In Apex, I’ve found that abstract utility classes with all-static methods are the equivalent of a Java/Spring service layer (without dependency injection). In practice they behave the same as a stateless singleton class anyway. We have dozens of these in our app, which are used to do anything servicey, such as the describe call caching you mentioned.
When you’re in an environment that is born and dies within the scope of a single (single-threaded) request, the singleton pattern is irrelevant. Static achieves the same ends, including state sharing within the request if that’s what you need.