Quantcast
Channel: Alternatives to the singleton pattern - Software Engineering Stack Exchange
Viewing all articles
Browse latest Browse all 11

Answer by gnasher729 for Alternatives to the singleton pattern

$
0
0

It depends very much what you mean by singleton. My definition: A “singleton instance” (not class) is an object that serves a specific purpose, that should be exclusively used for that purpose, that is automatically created the first time it is needed or earlier, and stays in existence as long as the program runs.

The usual method to get a singleton instance is to call a function or class method which returns the singleton instance. That method can return an instance of a subclass of the declared type, or an instance of any class supporting some interface. You can safely store references to singleton instances or pass them around, including to constructors, which allows dependency injection.

You definitely don’t use static class instances (they get destructed before the application ends, and they prevent changing the class without changing all your code).

And the big one: Don’t use singleton instances when you use two or more. In ios 16 you can have one process that looks like it is running multiple instances of an application. So objects referring to an application as a whole cannot be singletons anymore. Or simpler, you cannot have a singleton representing your printer if you have two printers.


Viewing all articles
Browse latest Browse all 11

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>