Singleton Design Pattern : Creational Pattern

Share the Article

What

Singleton design pattern is a type of creational pattern which controls the creation of the instance of a class. It mainly ensures to have only one instance of a class through out the application . It also provides access to that instance globally.

Why

Let us take an example of an application which need to access date and time of system at random places. Since time of system will be same at any instance so our requirement to create a timerClass and getDataAndTime( ). Ideally we need only one timerClass Object throughout our application.

Example without using Singleton Design Pattern

Basic approach is to a declare timerClass object as global variable and access it from multiple places. Lets see code below:

#include<iostream> //main header using namespace std; //for namespace class timerClass { public: timerClass() { cout<<"TimerClass Object created" <<endl; } void getCurrentDateandTime() { cout<<" Date is XX and Time is YY" <<endl; } }; // Default initialization timerClass *timerClassptr =NULL; // global object created void performJob1(void) { // Initialization on first use if (!timerClassptr) //need to check valdity timerClassptr = new timerClass; cout<<"Job1 1 Done at "; timerClassptr->getCurrentDateandTime(); } void performJob2(void) { if (!timerClassptr) // need to check validity timerClassptr = new timerClass; cout<<"Job2 Done at "; timerClassptr->getCurrentDateandTime(); } int main() { if (!timerClassptr) timerClassptr = new timerClass; cout<<"Main job started at"; timerClassptr->getCurrentDateandTime(); performJob1(); performJob2(); }

Output

code using global variable instead of singleton pattern

In above example we see that there is need to check for existence of the global timerClassPtr at every place. Therefore, such check ensures if it is NULL or not and then accordingly we need to construct it .

In the above approach, firstly, wherever we need to use timerClass we need to check validity of the global pointer. And secondly, we are pushing the creation logic at several places which let to code pollution. In conclusion, the application ultimately leads to creation of timerClass object from several places.

Such cases, where we need a single resource, the singleton design pattern is the best fit .

How

Lets try to update the above example with singleton design pattern. We need to follow specific rules for using this design pattern.

1. Hide the constructor of class

Firstly, the class needs to keep constructor as private or protected. This is based on the requirement that the construction of object should not possible from outside the class.

Secondly, the class also needs to make move constructor and assignment operator as private or protected in similar way.

private or protected: timerClass(); timerClass(const timerClass &); timerClass& operator=(const timerClass&);

In C++11, there is an additional requirement to make move constructor and move assignment also private.

2. Declare static & private instance inside class

Secondly, the class needs to declare an instance as static & private inside.

static timerClass *timerClassptr ;

3. Define a public function for getting instance

Thirdly, the class shall provide a static function in public scope, example, getInstance( ). This function shall take the ownership of creating and returning valid instance of the class. Any client code will use this public function to get access to class instance.

static timerClass *getInstance()

Using timerClass example with singleton design pattern

#include<iostream> //main header using namespace std; //for namespace class timerClass { private: static timerClass *timerClassptr ; timerClass() { cout<<"TimerClass Object created" <<endl; } public: static timerClass *getInstance() { if( timerClassptr == NULL) timerClassptr = new timerClass; return timerClassptr; } void getDataandTime() { cout<<" Date is XX and Time is YY" << endl; } }; // Default initialization timerClass* timerClass::timerClassptr =NULL; void performJob2(void) { timerClass::getInstance()->getDataandTime(); } void performJob1(void) { timerClass::getInstance()->getDataandTime(); } int main() { timerClass::getInstance()->getDataandTime(); performJob1(); performJob2(); }

Output

simple example of singleton design pattern

As seen above now, the singleton design pattern makes the function performJob1( ) and performJob2( ) much easier & cleaner. Therefore, there is no need to check the validity and take burden of calling constructor. Ultimately, the ownership of single instance is with singleton class. This ensures that user no longer worry about creation and maintenance of the single object.

Deleting the instance created by singleton design pattern

For singleton class, we have created timerClassptr as a static pointer inside the class. As per C++ rule, a static pointer will not by automatically cleaned-up by the destructor. In order to delete the global instance, we can follow one of below approach

A) Using a static function for deletion

Define a static function, example, deleteInstance( ) inside the class. We shall call it specifically at the end of application.

#include<iostream> //main header using namespace std; //for namespace class timerClass { private: static timerClass *timerClassptr ; timerClass() { } public: static timerClass *getInstance() { if( timerClassptr == NULL) timerClassptr = new timerClass; return timerClassptr; } void getDataandTime() { cout<<" Date is XX and Time is YY" <<endl; } static void deleteInstance() { if( timerClassptr != NULL) { delete timerClassptr; timerClassptr = NULL; } cout<< "TimerClass Object deleted" << endl; } }; // Default initialization timerClass* timerClass::timerClassptr =NULL; void performJob2(void) { timerClass::getInstance()->getDataandTime(); } void performJob1(void) { timerClass::getInstance()->getDataandTime(); } int main() { timerClass::getInstance()->getDataandTime(); performJob1(); performJob2(); timerClass::deleteInstance(); }

Output

deleting a singleton class  instance

B) In C++ 11, use smart pointers for singleton

In C++ 11, we have shared pointers which we use for managing a static instance. As per C++11 guideline of shared_pointer, this shall take care of deletion.

Please refer below example for using std::shared_ptr < >

#include<iostream> //main header #include <memory> //for smart pointers using namespace std;//for namespace class timerClass { private: static std::shared_ptr<timerClass> timerClassptr; public: static std::shared_ptr<timerClass > getInstance() { if( timerClassptr == NULL) timerClassptr = std::make_shared<timerClass>(); return timerClassptr; } void getDataandTime() { cout<<" Date is XX and Time is YY" <<endl; } ~timerClass() { cout << "~timerClass" << endl; } }; // Default initialization std::shared_ptr<timerClass> timerClass::timerClassptr=NULL; void performJob2(void) { timerClass::getInstance()->getDataandTime(); } void performJob1(void) { timerClass::getInstance()->getDataandTime(); } int main() { std::shared_ptr<timerClass> s1= timerClass::getInstance(); s1.get()->getDataandTime(); performJob1(); performJob2(); }

Output

using singleton design pattern with smart pointers

Using singleton design pattern in a multithreaded application

Till now we have seen singleton class application with only one main thread. In order to support singleton class for a multithreaded application, we need to take care of Race Condition also.

Lets update now the timerClass application for enabling two threads performing job1 and job2 in parallel along with the main thread . We need to synchronize the creation and deletion of the instances so that thread can perform their jobs as expected.

#include<iostream> //main header #include<thread> //for threads #include<mutex> //for mutex using namespace std;//for namespace std::mutex m1; class timerClass { private: static timerClass *timerClassptr ; timerClass() { } public: static timerClass *getInstance() { m1.lock(); if( timerClassptr == NULL) timerClassptr = new timerClass; m1.unlock(); return timerClassptr; } void getDataandTime() { cout<<" Date is XX and Time is YY" <<endl; } static void deleteInstance() { m1.lock(); if( timerClassptr != NULL) { delete timerClassptr; timerClassptr = NULL; } m1.unlock(); cout<<" TimerClass Object deleted" <<endl; } }; // Default initialization timerClass* timerClass::timerClassptr =NULL; void performJob2(void) { timerClass::getInstance()->getDataandTime(); } void performJob1(void) { timerClass::getInstance()->getDataandTime(); } int main() { timerClass::getInstance()->getDataandTime(); std::thread mythread1 (performJob1); std::thread mythread2 (performJob2); mythread1.join(); mythread2.join(); timerClass::deleteInstance(); }

Output

code using singleton design pattern with multithreading

Pros & Cons of Singleton Design Pattern

Pros

  1. The singleton design pattern creates manageable code for classes who need only one instance.
  2. Singleton class takes care of creation of instance. The user need not take the burden of managing of the instance.
  3. There is no need for user to check validity of instance.
  4. This can be used efficiently in Multithreaded application also.

Cons

  1. The introduction of a static instance into the system can make unit testing difficult.
  2. Us of too many singleton classes in one application will pollute the code.
  3. User need to take care of deletion of objects at the end of application.

Main Funda: Singleton pattern is useful for managing critical resources.

Advanced C++ Topics

Abstract Factory Design Pattern
Class Template Argument Deduction in C++17
What is a Tuple, a Pair and a Tie in C++
C++ Multithreading: Understanding Threads
What is Copy Elision, RVO & NRVO?
Lambda in C++11
Lambda in C++17
std::chrono in C++ 11
Thread Synchronization with Mutex
Template type deduction in functions
How std::forward( ) works?
How std::move() function works?
What is reference collapsing?

Share the Article

239 thoughts on “Singleton Design Pattern : Creational Pattern

  1. Jeśli chcesz od razu przetestować możliwości, jakie dają bonusy bez warunków obrotu, dołącz do innych graczy, którzy zaufali rekomendowanym przez nas kasynom online. Na naszej liście znajdziesz najlepsze kasyna online z bonusami bez warunków obrotu. Możesz sprawdzić je już teraz. Który z nich jest lepszy, brak bonusów zakładowych lub bez depozytu? Czy naprawdę nie ma żadnego depozytu, które nie ma zakładów kasynowych? Jak powiedzieliśmy wcześniej, bonusy kasyna bez przepisów obrotowych są tymi, które wymagają “zero zakłady” przez warunki bonusowe. W rezultacie gracze są w stanie spełnić swoje wygrane z tych bonusów dalej. Nie ma to w przypadku zachęt bez depozytów, zwłaszcza podanych do rejestracji. Kasyna zapewniają swobodne spiny lub gotówkę, aby przyciągnąć cię i pobyt z nimi, nie jest to konibolment charytatywny, który otrzymasz i może się wycofać, brzmi to bezcelowe. https://johnnyhapf209753.blogitright.com/13567540/kiedy-kasyno-online-w-polsce Załóżmy, że ta wynosi x30. Oznacza to, że do wypłacenia takiej kwoty z konta bonusowego będziesz musiał zagrać za przynajmniej 300 złotych w innych grach. Nie ma znaczenia w jakich, a także to, czy zrobisz to jednego dnia. Pamiętaj jednak, że musisz zmieścić się w limicie czasowym bonusu. Jeżeli skończy ci się czas, wszystkie zdobyte środki przy użyciu bonusu przepadną. Powoduje to, że wiele bez depozytu bonus kasyno ma nieco większy czas wykonania niż inne promocje – a jego dokładny limit czasowy, jak i obrót, zawsze możesz sprawdzić w regulaminie promocji, którą znajdziesz na stronie kasyna. Jak widzisz oba bonusy są atrakcyjne i ciekawe – i z pewnością mogą do kasyna przyciągnąć nowych graczy. Jak je odebrać? Zwykle aktywują się w momencie rejestracji konta, chociaż czasami trzeba zaznaczyć odpowiednią opcję w oknie z zakładaniem konta. Warto przeczytać regulamin takiej promocji przed rejestracją, by upewnić się, że nic cię nie ominie! W innych przypadkach konieczne będzie wpisanie specjalnego kodu promocyjnego, również w okienku rejestracji. Ostatnim z przypadków może być aktywacja bonusu z panelu zarządzania kontem. Z tych wszystkich opcji to jednak ta pierwsza jest najczęściej spotykana. Poniżej opisujemy obie te promocje jeszcze dokładniej.

  2. of course like your web-site but you need to take a look at the spelling on several of your posts. Many of them are rife with spelling problems and I to find it very troublesome to tell the truth however I will definitely come back again.

  3. Kadın Sneakers. Kadınlar modern yaşantılarında rahat hareket
    etmek ve enerjik bir stile sahip olmak için sıklıkla kadın sneakers giymeyi tercih ediyorlar.

    Ofiste, parkta, spor yaparken veya alışveriş
    yaparken vücut sağlığını ve rahatını düşünenler bayan sneakers modellerini tercih ediyor.İlhamını doğadan alan ve ayrıcalıklı bir görünüme dikkat çeken Favgi.

  4. Cannabis can harm kids, but scare tactics are ineffective. The best way to reach a young adolescent is to honor their intellect, treat them as the expert in their own life, avoid lecturing, focus on developing their critical-thinking skills, and give them age-appropriate, factual information. Cannabis products are also useful for chronic pain management, and are undeniably associated with better outcomes than opiates in the vast majority of cases . A study of Medicare Part D patients found that states with medical marijuana prescribed about 1.79 million fewer doses of opiates between 2010 and 2015, with hydrocodone and morphine prescriptions decreasing the most. Marijuana use is a significant advance in pain management, as exposure to opiates in a medical setting is often a gateway to addiction . On that front, the advance of legal marijuana is helpful for managing pain in vulnerable populations, including college students who may not want to take the risk of using opiates for pain. https://gregoryizpe198643.tusblogos.com/13239512/medical-marijuana-centers London, Ohio Yes, a business licence or temporary use permit for retail cannabis can be cancelled or revoked if the terms and conditions of the business licence or temporary use permit are not met or if bylaw infractions occur.  As well, if Council were to adopt a Non-medical Retail Cannabis Policy, staff could recommend refusal of an application if the criteria from the policy were not met. Warning: This product has intoxicating effects and may be habit forming. Smoking is hazardous to your health. There may be health risks associated with consumption of this product. Should not be used by women that are pregnant or breast feeding. Marijuana can impair concentration, coordination, and judgment. Do not operate a vehicle or machinery while under the influence of this drug. For use only by adults twenty-one and older. Keep out of the reach of children.

  5. 15851 Dallas Parkway, #600 Das City Club Casino bietet seinen Spielern den kostenlosen Download, Installation und Verwendung der Glücksspielsoftware. Spieler können die Software leicht von der Seite herunterladen. Das Online Casino bietet auch eine Flash-Version zum sofortigen Spiel der Spiele an, so dass Spieler ihre Lieblingsspiele spielen können, ohne die Software herunterladen zu müssen. Die Webseite ist ebenfalls mit 256bit SSL gesichert, so dass die übermittelten Informationen immer sicher und zuverlässig behandelt werden. Die Spiele, die im City Club Online Casino angeboten werden, wurden von einem der berühmtesten Glücksspielsoftwareunternehmen entwickelt – Playtech. City Club Casino offers you not only service at the appropriate level, but also inimitable rewards program, as well as impressive selection of games and huge jackpots. It has very reputable license and its activity is regularly examined by independent experts. So just create your Real Account now and get attractive promotions. https://tlebeauty.com/community/profile/janiem865812468/ Blackjack is played with a standard international deck of cards with the Jokers removed, leaving 52 cards. Originally the game was played with a single deck. However, as a counter measure to card counting, casinos introduced multi-deck games, based on the false assumption that if there were more cards in play it would be harder for the card counter to keep track of them all. As a result, Blackjack is now usually offered in either single deck, double deck, 4 deck, 6 deck or 8 deck variants. It should be noted that there are exceptions in online casinos where far larger numbers of decks can be used than would be practical to manage offline. If a Player who wants to play Games (other than Play-for-Free Games, Sports Betting Games Played Online and Draw Based Lottery Games Played Online) has both Bonus Funds and Unutilized Funds in their Player Account (regardless of whether the awarding of the Bonus Funds preceded or followed the credit of notional funds to the balance of the Player Account, whether resulting from a deposit of funds with OLG by the Player or the winning of a Prize by the Player), the Unutilized Funds will be used first to play the eligible Games until all of the Unutilized Funds have been utilized, following which time the Bonus Funds will be used. Winnings from wagers placed with Bonus Funds are added to the Bonus Funds balance.

  6. พวกเขาเติบโตเพิ่มอีก
    1 ถึง 2 นิ้วในปีหรือสองปีหลังจากช่วงเวลาแรกของพวกเขา นั่นคือเมื่อพวกเขาถึงวัยผู้ใหญ่
    ผู้หญิงส่วนใหญ่เข้าสู่วัยผู้ใหญ่ตอนอายุ 14 หรือ 15 ปี.

  7. The following time I read a blog, I hope that it doesnt disappoint me as much as this one. I imply, I do know it was my choice to learn, but I actually thought youd have something interesting to say. All I hear is a bunch of whining about something that you would fix if you happen to werent too busy on the lookout for attention.

  8. When I initially commented I clicked the -Notify me when new comments are added- checkbox and now every time a comment is added I get 4 emails with the same comment. Is there any method you’ll be able to remove me from that service? Thanks!

  9. The HPA axis, also called the stress axis, is a major component of the neuroendocrine system that controls the body s response to environmental stressors psychological, physical or infectious and regulates many of the body s physiological processes such as metabolism, reproduction, growth, mood and emotions and the immune function. how much is clomid It can be easy for resentment to build when we are not careful about the posture of our hearts as we wait.

  10. Sexual stimulation that leads to an erection causes the production and release of nitric oxide in the penis п»їcialis Nicholas Hewlett, head of St Dunstan s College private school in southeast London, said staff were worried by a righteous generation of children who were looking for their teachers to trip up on even small, persistent slights

  11. Nice post. I learn something more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a little something from their store. I’d prefer to use some with the content on my blog whether you don’t mind. Natually I’ll give you a link on your web blog. Thanks for sharing.

  12. Having read this I thought it was very informative. I appreciate you taking the time and effort to put this article together. I once again find myself spending way to much time both reading and commenting. But so what, it was still worth it!

  13. Es gibt viele Entwickler von Automatenspielen. Die bekanntesten von ihnen sind zum Beispiel: Download-Größe Zwar sind noch nicht alle unsere kostenlosen Glücksspiel-Slots auch für Nutzer von Smartphone und Tablet verfügbar, allerdings kannst du die beliebtesten Spielautomaten dank HTML5 Technologie mittlerweile sowohl mit einem Desktop PC, als auch mit einem Mobilgerät verwenden. Ja, nahezu jedes Automatenspiel funktioniert problemlos auf mobilen Endgeräten wie Smartphones oder Tablets. Dabei sind sämtliche Funktionen nutzbar. Die Darstellung passt sich automatisch der jeweiligen Bildschirmgröße an. Auf dieser Website findet man nur die besten kostenlosen Online-Slots, die hier sorgfältig sortiert sind, damit jeder Spieler ohne viel Aufwand in die Welt des Slots eintaucht. Germany Casino testet die Zuverlässigkeit aller Slots und bietet umfassende Bewertungen, so dass, wenn Sie die Slots besser erlernen möchten, stehen Ihnen hier alle notwendigen Informationen und Spezifikationen zur Verfügung. Es bleibt Ihnen nur Online Spielautomaten kostenlos zu testen. https://sparrowon.cds509.euginda.com/community/profile/tressaillingwor/ Reich werden im Online Casino: Jeder Mensch träumt von einem sorgenfreien Leben in finanzieller Sicherheit. Dabei wird jedoch unterschätzt, dass neben einer guten Portion Glück auch einige Strategien und Tipps beachtet werden sollten. Im folgenden Artikel gehen wir der Frage nach, ob man mit Online Casino Geld verdienen kann und mit welchen Strategien ihr eure Chancen verbessern könnt. Mit der persönlichen Anmeldung der Spieler zu den Onlinespielmöglichkeiten werden oft erste nützlichen Daten erhoben. Sind die Nutzer volljährig, solvent, nicht für Glücksspiele gesperrt, woher kommen ihrer Spieleinsätze und wohin sollen die Gewinne ausgezahlt werden, sind nur einige Werte, die hier gesammelt werden. Diese Informationen werden dann im Zuge der weiteren Verweildauer durch zusätzliche Auswertungen ergänzt. Welche Spiele werden bevorzugt, wie lange wird gespielt, welche Mittel werden dazu aufgewandt etc.

  14. hi!,I really like your writing so much! proportion we communicate extra approximately your article on AOL? I require a specialist in this house to unravel my problem. May be that is you! Looking forward to peer you.

  15. Nice read, I just passed this onto a colleague who was doing some research on that. And he actually bought me lunch since I found it for him smile Therefore let me rephrase that: Thanks for lunch! “We have two ears and only one tongue in order that we may hear more and speak less.” by Laertius Diogenes.

  16. Hey there! Quick question that’s entirely off topic. Do you know how to make your site mobile friendly? My blog looks weird when viewing from my iphone 4. I’m trying to find a theme or plugin that might be able to correct this issue. If you have any suggestions, please share. Thanks!

  17. Good – I should definitely pronounce, impressed with your web site. I had no trouble navigating through all the tabs and related information ended up being truly simple to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or anything, site theme . a tones way for your customer to communicate. Nice task.

  18. An impressive share, I just given this onto a colleague who was doing a little analysis on this. And he in fact bought me breakfast because I found it for him.. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the time to discuss this, I feel strongly about it and love reading more on this topic. If possible, as you become expertise, would you mind updating your blog with more details? It is highly helpful for me. Big thumb up for this blog post!

  19. World Class Kitchens began its pursuit of building dream kitchens and baths when Joe Vitale chose to pursue an independent venture focusing on best in class, innovative products, and exceptional design.  Joe’s foundation is a lifetime of construction experience supported by family generations of skilled craftsmen originating in Sicily. His avid love for the latest trends and skills can be found in his attention to detail within his truly World Class Kitchen designs. Generally speaking, if you are hoping to recoup some cost in eventually selling your home, a kitchen remodel should cost no less than 5 percent and no more than 15 percent of the value of your home. On average, Realtors surveyed by National Association of RealtorsⓇ (NAR) revealed that a kitchen upgrade or full remodel can expect to recover 50-59 percent of costs at sale, and 20 percent of realtors say a completed kitchen remodel helped close a sale on the home. https://team.triseries.bg/forum/profile/jurgenumr95215/ A: Because materials vary so drastically in quality, we cannot use average square foot price to cost out your kitchen remodel; One homeowner may want an over-the-top extravagant chef kitchen with top of the line marble, custom cabinets, custom inserts, reinforced pot rack, pot filler, kitchen island, butlers pantry, wet bar, and more. In addition to looking great, your kitchen needs to be functional and practical. Make sure you consult with a kitchen renovation expert when planning the layout of your kitchen. Remember the classic work triangle? Arrange the three features you use the most, closest to each other to avoid unnecessary trips.Pro Tip: Avoid rearranging the fundamental features of your kitchen like the fridge or sink. These are expensive changes that require more manpower. 

  20. What i don’t understood is in fact how you’re now not actually a lot more smartly-preferred than you may be now. You are very intelligent. You understand thus significantly in the case of this matter, made me individually consider it from a lot of varied angles. Its like men and women aren’t involved except it’s something to do with Girl gaga! Your individual stuffs outstanding. Always take care of it up!

  21. Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!

  22. I’m truly enjoying the design and layout of your website. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a designer to create your theme? Fantastic work!

  23. I do agree with all of the ideas you have presented in your post. They’re very convincing and will certainly work. Still, the posts are too short for starters. Could you please extend them a bit from next time? Thanks for the post.

  24. I think this is one of the most vital information for me.
    And i’m glad reading your article. But want to remark on some general
    things, The web site style is wonderful, the articles is really
    great : D. Good job, cheers

  25. Heya i’m for the first time here. I found this board and I
    find It truly useful & it helped me out much.
    I’m hoping to provide one thing back and help others like you aided me.

  26. Your style is so unique compared to other folks I have read stuff from.
    Many thanks for posting when you have the opportunity, Guess I will just book mark
    this page.

  27. Heya i’m for the first time here. I found this board and I
    find It truly useful & it helped me out much. I am hoping
    to give something back and aid others like you aided me.

Leave a Reply

Your email address will not be published. Required fields are marked *