Design Patterns - Singleton Pattern | Explanation and Implementation in C++

Поділитися
Вставка
  • Опубліковано 21 лип 2024
  • ►Software Design and Design Patterns Playlist: • C++ Software Design an...
    ►Find full courses on: courses.mshah.io/
    ►Join as Member to Support the channel: / @mikeshah
    ►Git Repo: github.com/MikeShah/DesignPat...
    ►Lesson Description: In this lesson I show you how to implement a creational design pattern in C++ known as the singleton. This is a controversial pattern to many in that it can be misused, however, the pattern itself can be useful when we truly need only 1 point of access for a specific class (e.g., a file system or logger). This lesson will also refresh you on the idea of 'static' which is a clean way to implement the singleton pattern.
    Useful resource on understanding static en.cppreference.com/w/cpp/lan...
    00:00 Design Patterns are not perfect
    00:58 Creational Design Pattern
    2:25 Sample Logger Class
    4:10 Creating multiple instances of an object
    5:15 Utilizing access modifiers of class for constructor
    6:06 Idea of a GetInstance member function
    7:06 The static keyword
    7:50 static function example
    10:22 Practical use case of static in a class
    11:00 Initializing static member variables
    13:30 A static pointer to instance of our class as member variable
    15:40 Utilizing a member function from our single instance
    16:50 Creating a static member function
    17:37 Implementing our logger class
    19:10 Allocating memory for our pointer
    20:50 Adding messages to our logger
    22:18 Careful with returning pointers to member variables
    24:20 Design to protect your clients of your API
    25:10 Create the static variable within GetInstance
    27:30 Other design considerations and closing
    ►UA-cam Channel: / mikeshah
    ►Please like and subscribe to help the channel!
    ►Join our free community: courses.mshah.io/communities/...
  • Наука та технологія

КОМЕНТАРІ • 53

  • @user-ql7pw7ld1n
    @user-ql7pw7ld1n 3 місяці тому +2

    Understood it fully today, after learning about static objects, everything is clear now.. :)

  • @michaelswahla4927
    @michaelswahla4927 5 місяців тому +2

    Beautiful explanation mike! I had trouble on understanding why people would use Singletons and how static memory worked! Keep up the great work, you are INSANELY underrated! One of the best! :)

    • @MikeShah
      @MikeShah  5 місяців тому

      Cheers, thank you for the kind words!

  • @devsutreja5053
    @devsutreja5053 2 роки тому +7

    Best explanation of Singleton ever!
    Thanks Mike!!

    • @MikeShah
      @MikeShah  2 роки тому

      Thank you for the kind words!

  • @Altekameraden79
    @Altekameraden79 8 місяців тому +1

    Holy smokes, three weeks into learning C++ with only two semester of MATLAB behind me 10 years ago and I guess correctly on static, sort of as I though static_cast would be answer.

  • @ByChris
    @ByChris День тому +1

    Excellent explanation!

  • @robertstrickland9722
    @robertstrickland9722 2 роки тому +8

    Thanks!

    • @MikeShah
      @MikeShah  2 роки тому +2

      Amazing, thank you for the wonderful and generous donation!

    • @robertstrickland9722
      @robertstrickland9722 2 роки тому +1

      @@MikeShah Generous donation for generous (and thorough) coursework!

    • @MikeShah
      @MikeShah  2 роки тому +1

      @@robertstrickland9722 more to come!

  • @bharatpatidar3693
    @bharatpatidar3693 Рік тому +1

    Just Loving it 🙏

  • @robertstrickland9722
    @robertstrickland9722 2 роки тому +1

    I'm having a bit of trouble trying to understand how you can initialize the s_instance on a global scale even though it's a private member of a class.

    • @MikeShah
      @MikeShah  2 роки тому

      Couple of videos coming up on 'static' here: ua-cam.com/video/hIsE0HiP1E8/v-deo.html and here ua-cam.com/video/IPCEBHWgRr8/v-deo.html (to be released shortly) that I think will help clarify how 'static' variables in classes are shared amongst all instances of a class.

  • @damondouglas
    @damondouglas 4 місяці тому +1

    Thank you so much for this. I experimented with "what if I wanted to replace the Logger* with std::unique_ptr". What was interesting is that I had to declare "std::unique_ptr Logger::s_instance;" outside the class and then "Logger::s_instance = std::make_unique();" inside GetInstance(), returning *s_instance. However, when I removed the declaration outside the class and had "std::unique_ptr s_instance = std::make_unique();" inside the GetInstance(), it instantiated new Logger instances. In your implementation, would you have had to delete the *s_instance somewhere or is this taken care of for us because it's static?

    • @MikeShah
      @MikeShah  3 місяці тому +1

      Because it is static, it would be cleaned up on program termination :)

    • @pradeepjagdale7768877650
      @pradeepjagdale7768877650 Місяць тому

      @@MikeShah I feel it will clean the pointer not the object of Logger() as we have used a new Logger()

  • @xinking2644
    @xinking2644 2 роки тому

    great video, helps a lot !

    • @MikeShah
      @MikeShah  2 роки тому

      Thank you for the kind words!

  • @letslearn1703
    @letslearn1703 9 місяців тому +1

    Please do a video on proxy and skeleton design pattern

  • @carlosrnardi
    @carlosrnardi 2 роки тому +1

    Hello Mike, that is a very nice example of it!
    I have two questions, I understand we need to use mutex to be thread safe specially when we add new text to the log in this case, but why we should use mutex when GetInstance return the address of the object? since static will garantee we only have one copy of it. My second question is about the destructor, I notice it is never called, is this the standard behavior of singleton?, since the object needs to keep availble anytime if needed.
    Thanks Mike, awesome video!

    • @MikeShah
      @MikeShah  2 роки тому +1

      Hi Carlos,
      Yes, correct on part one since we have static the variable will only be initialized once, and we'll only have one address returned so no need for a mutex. As for the destructor, static variables last the duration of the program, so the destruction is never called (it's kept available after the first allocation for the lifetime of the program). We could create a helper function to destroy any allocated memory if we truly wanted to, and sometimes folks will write a 'destroy' function, or a 'restart' type of function to reallocate.

    • @carlosrnardi
      @carlosrnardi 2 роки тому +1

      Thanks@@MikeShah for the explanation, Your videos are awesome!!

    • @MikeShah
      @MikeShah  2 роки тому

      @@carlosrnardi You are most welcome! Thank you for the kind words!

    • @_w62_
      @_w62_ 7 місяців тому +1

      @@MikeShah Would shared_ptr be the suitable choices for the 'restart' functions? If not, what would be the recommended patterns for resoure management in the singleton pattern? Thanks.

    • @MikeShah
      @MikeShah  7 місяців тому

      ​@@_w62_Depends on what you are doing with the singleton -- in general we try to use unique_ptr, and in your restart() you could 'move' to a newly allocated pointer in 'restart'

  • @k0185123
    @k0185123 5 місяців тому +1

    amazing!!!

  • @nagenHARP
    @nagenHARP 4 місяці тому +2

    you are genius . 🙏

    • @MikeShah
      @MikeShah  4 місяці тому

      Thank you for the kind words!

  • @letslearn1703
    @letslearn1703 9 місяців тому

    Hi Mike I have a doubt , if we define a class member variable, then we need to allocate the memory by declaring the same variable outside class scope. But if we have a static variable in member function of a class we need not to declare the variable out side class for memory allocation. I could not understand how memory gets allocated for it, can you please explain. You have used static variable class function in singleton class design pattern video. Please explain this.

    • @MikeShah
      @MikeShah  9 місяців тому

      I believe the static variables inside of functions are allocated already -- the issue with the static class member variables is they need a concrete instantiation defined somewhere in a file (so the generated .object file knows where to store them).

    • @letslearn1703
      @letslearn1703 9 місяців тому

      @@MikeShah Great video , thanks for your comments

    • @MikeShah
      @MikeShah  9 місяців тому

      @@letslearn1703 Cheers!

  • @davidpinheiro5295
    @davidpinheiro5295 5 місяців тому

    Alternatively you can use "inline" to initialize static member objects inside a class, think this makes it more intuitive!

    • @MikeShah
      @MikeShah  5 місяців тому

      Yes! It actually makes things much more clean :)

  • @pedrolobo9835
    @pedrolobo9835 Рік тому

    Hey! Great video, but I think this code might leak memory, because I didn't see the delete operator anywhere.

    • @pedrolobo9835
      @pedrolobo9835 Рік тому +2

      How about?
      static Logger& GetInstance(){
      static Logger sInstance;
      return sInstance;
      }

    • @MikeShah
      @MikeShah  Рік тому +1

      @@pedrolobo9835 I should probably delete the pointer, you're right. The trade-off is that. by using the pointer I don't have to allocate ever if I never use the class -- though of course I might cause a memory leak :)

    • @MikeShah
      @MikeShah  Рік тому +2

      Using std::unique_ptr would be the right thing to do in an even better implementation of singleton :)

  • @julianbittner4822
    @julianbittner4822 Рік тому +1

    Do you have courses on udemy?

    • @MikeShah
      @MikeShah  Рік тому

      My courses are all slowly migrating to courses.mshah.io

  • @nagenHARP
    @nagenHARP 3 місяці тому +1

    what if i like to use as below :
    #include
    #include
    #include
    using namespace std;
    class Singelton
    {
    private:
    vectormessage;
    Singelton(){
    cout

    • @MikeShah
      @MikeShah  3 місяці тому

      That is also fine -- there's a variety of ways to setup singletons with some subtle trade-offs. If you use a pointer, then you only allocate if you use the Singleton for example. This may or may not matter depending on the size of the object.

  • @user-ql7pw7ld1n
    @user-ql7pw7ld1n 3 місяці тому +1

    Understood nothing... after 13:30

    • @MikeShah
      @MikeShah  3 місяці тому +1

      This video on the 'static' keyword may be useful, as that is introduced at the 13:30 mark :) ua-cam.com/video/hIsE0HiP1E8/v-deo.html

    • @user-ql7pw7ld1n
      @user-ql7pw7ld1n 3 місяці тому

      @@MikeShah Hi mike thanks for the video link.. I just saw full video. I am known to behavior of static , so only thing new is "static variables are stored in binary",...Now back to the main thing, in the singleton video, What I didnt understood is that --------> you are making a static instance of the class itself, that too inside the class.. This is really confusing..

    • @MikeShah
      @MikeShah  3 місяці тому

      @@user-ql7pw7ld1n Constructor is private, so cannot be made. The way to get around that is to have a single 'static' (stored in the binary as you said) and you can instantiate that value at compile-time, or otherwise instantiate it in a public member function.

    • @user-ql7pw7ld1n
      @user-ql7pw7ld1n 3 місяці тому

      @@MikeShah ok...got an outline..im studying about "static instance" which is core concept of singleton ig...