Pattern Postulate - The Singleton
I decided to flip through a little book called "Head First Design Patterns" today. It was 700 pages long, so I assumed it contained something good. In reality, it was about 700 pages of bulk. I guess for people who don't understand something immediately, they'd have 50 pages to learn it... The design patterns in the book were kind of outdated and bulky, too. So I've decided to make an easy-to-read blog post series on design patterns. Welcome to the first post of Pattern Postulate! (I don't even know what a postulate is, but it sounds catchy)
A singleton is an object that only has one instance of itself. Now you may be wondering, "Why can't I just make a static class?" The answer lies in the fact that static classes are messy for holding things like variables. They can't use the "this" keyword to reference themselves. They can be initialized, but multiple times. It's just kind of funky to refer to a set of methods as something other than an object.
On the other hand, singletons are objects. They can be passed through methods, etc. and even be EXTENDED! Whoa. But they still only have one instance. It's part object, part static class, and all fun! (That's a pun on a saying from my Latin class) So anyways, to make a singleton, you have to write something like this:
public class MySingleton { private static MySingleton instance = new MySingleton(); private MySingleton() { } public static MySingleton getInstance() { return instance; } }
We initialize the singleton in a private, static variable and retrieve it through a public, static method. Thus we can easily get the only instance of MySingleton ever created and ever will be created through "MySingleton.getInstance()". We have an object that we can use as one, instead of an annoying static class.
I'm in no way saying that this is always the correct thing to do. For a Math class, for example, you don't want to make a new Math object and do object.sin(). That's just weird. For util-style functions like that, you should be using static methods. You should also use static methods for factories that don't require any class parameters. (I'll cover factories soon) But for something like a database class that would hold something like a JDBC url or if you have a resource manager class that requires you to store a few Maps of resources, you'd want a singleton.
And that's it! 4 paragraphs of information as opposed to 20 Head First pages.
Thanks for reading my post! If you enjoyed it or it helped you, please consider liking/tweeting this page, commenting, or following me on GitHub or Twitter!