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
1
|
|
1
|
|
Here’s an implementation of the Singleton Pattern in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
And here’a an implementation in Objective C
1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
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.