Make a class impossible to instantiate twice: every call to its constructor must return the very same object, and the constructor body must run only once.
Python — implement SingletonMeta.__call__. A metaclass's __call__ runs whenever the class is called, so it decides what MyService() returns:
class MyService(metaclass=SingletonMeta):
...
MyService() is MyService() # TrueJavaScript / TypeScript — implement singleton(Class), which returns a Proxy around the class. Its construct trap intercepts new, exactly like the metaclass intercepts the call:
const MyService = singleton(class { ... });
new MyService() === new MyService(); // trueThe starter defines MyService (whose constructor counts how often it runs) and OtherService. solve(check) answers one question:
check | Returns |
|---|---|
'same' | whether two instantiations give the same object |
'isInstance' | whether that object is really a MyService |
'initCount' | how many times the constructor ran after three instantiations |
'sharedState' | a counter bumped on the first instance, read through the second |
'perClass' | whether MyService and OtherService get different singletons |
Sample tests