This one’s gonna be short. Honestly, I don’t know how last week’s article about static methods went so long.
Singletons get a bad rap, being called Anti-patterns, and for good reason. The biggest reason given against Singletons is that they’re global state, which is bad. If you want a stateful “Singleton”, there are ways to restrict the application to only having a single instance, even if the class can have multiple instances. While this still largely equates to global state, at least it opens up the possibility of test doubles and makes the “Singleton” itself that much easier to test.
But I’m not here to nag about stateful Singletons; there’s already plenty of that on the interwebz. No, I’m here to tell that there can be an okay usage for Singletons: as Strategies. Singletons don’t have to be stateful. If you have a stateless Strategy type, making it into a singleton can actually be helpful, reducing the memory overhead of potentially extra instances of the class. Often, you’ll want to lazily load it.
Python actually had an interesting way of doing Singletons that I’ve never actually even heard anyone talk about. What’s interesting about classes in Python is that they can be used just like any other instance, so you can just put static methods on a class and use it like an instance.
For an example, say we have a Strategy interface/protocol with the methods
strat2(), you can make a Strategy class like this:
class AStrategy: @staticmethod def strat1(): ... @staticmethod def strat2(): ...
This class can be used as an instance of a Strategy:
You can do that with static methods in other languages too, but the classes in those languages can’t be passed in as instances of a Strategy type. In Python, you can just pass in
AStrategy as an instance:
You barely have to do anything special to get a class to be a Singleton in Python; it’s pretty neat. It even works with stateful Singletons, but that’s bad, remember?