Singleton Pattern is one of the famous design patterns from the Gang of Four. Even though nowadays it is considered as an anti-pattern, it has served us well in the past. In Singleton pattern, a class has just one instance throughout its lifetime and that instance is shared between multiple clients. Singleton class has two responsibility, first to ensure that only instance of the class gets created and second, provide a method getInstance() so that everyone can get access to that single instance i.e. global access. One of the issue, faced by Singelton design pattern in the multi-threading program is to ensure that just one instance of the class gets created, even if multiple clients called getInstance() method same time. Many programmers solved this problem by making whole getInstance() method synchronized, which results in poor performance because every time a thread enters a synchronization method, it acquires the lock and while it's been inside the method, no other thread are allowed to enter, even if they are not creating instance and just accessing already created instance. How do you solve this problem? Well, you can use Double checked locking idiom, which you learn in this article. Btw, if you are curious about why Singleton is considered anti-pattern, I highly recommend the book Games Programming Patterns by Robert Nystrom, though examples are in C++, it's one of the most readable book on design pattern, you won't feel bored or cheated.
Read more »
No comments:
Post a Comment