Design Patterns — Singleton
Here’s my second post on Design Patterns. So, this post is going to throw some light on the Singleton Patterns.
In software engineering, the Singleton Pattern is a design pattern that restricts the instantiation of a class to one object
So one might wonder why would you need to implement a Singleton? There are many scenarios where we’d rather have just one instance of a particular class. For eg.
- The class which instantiates the DB connection
- It can be used as a replacement to a Global Variable
Here are some of the advantages of using a Singleton
- Only one instance of the class will exist
- This saves up on memory
- Allows one to share data amongst classes without actually passing around objects
Here are a few examples where you must have used a Singleton
Runtime.getRuntime().exec(new String[] {"echo", "Hello, world!"});
[UIApplication sharedApplication].delegate;
Here’s an implementation of the Singleton Pattern in Java
And here’a an implementation in Objective-C
So thats how you make use of Singletons. This is one Design Pattern you will use on a regular basis. Will update this article with more samples and issues related to thread safe creation of singletons.
EDIT : Added a slightly better way to manage Singletons in Objective C. A more detailed explanation and variations to this can be found in the next post.
Originally published at mariostallone.github.io on January 14, 2013.