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

Answer by Michael Borgwardt for Alternatives to the singleton pattern

$
0
0

Most people (including you) completely misunderstand what the Singleton pattern actually is. The Singleton pattern only means that one instance of a class exist and there is some mechanism for code all over the application to get a reference to that instance.

In the GoF book, the static factory method that returns a reference to a static field was just an example how that mechanism might look like, and one with severe drawbacks. Unfortunately, everyone and their dog latched onto that mechanism and thought it was what Singleton is all about.

The alternatives you cite are in fact also Singletons, just with a different mechanism for getting the reference. (2) clearly results in too much passing around, unless you need the reference in only a few places near the root of the call stack. (1) sounds like a crude dependency injection framework - so why not use a real one?

The advantage is that existing DI frameworks are flexible, powerful and well-tested. They can do much more than just manage Singletons. However, to fully use their capabilities, they work best if you to structure your application in a certain way, which is not always possible: ideally, there are central objects which are acquired through the DI framework and have all their dependencies transitively populated and are then executed.

Edit:Ultimately, everything depends on the main method anyway. But you're right: the only way to avoid the use of global/static completely is by having everything set up from the main method. Note that DI is most popular in server environments where the main method is opaque and sets up the server and application code consists basically of callbacks which are instantiated and called by the server code. But most DI frameworks also allow direct access to their central registry, e.g. Spring's ApplicationContext, for "special cases".

So basically the best thing people have come up so far is a clever combination of the two alternatives you mentioned.


Viewing all articles
Browse latest Browse all 11

Trending Articles



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