jeudi 12 août 2021

How do I synchronize the Singleton Pattern?

I'm learning about the Singleton Pattern. You can find something about it here https://en.wikipedia.org/wiki/Singleton_pattern.

I'm learning it from from the "Head First Design Patterns" book and they specifically say that synchronization is one of the bigger problems with this patterns.

They have 2 ways to handle it in Java.

  1. They Synchronize the GetInstance() method:

    • in Java they simply do this using the synchronized keyword public static synchronized Singleton GetInstance(){...
    • I think this is the best way to do it in C++ but I could not find a good way to do it, almost all of the ways I found is using global variables, and well... This pattern should in stop the use of the global variables and makes it kind of ironic.
  2. Use eager Instantiation:

    • the other way they do it using eager Instantiation, meaning they instantiate create the object and just return the creation with the GetInstance() method.

    This in C++ can be done like this: Singleton *Singleton::UniqueInstance = new Singleton(); (You would still have to do it outside the class because of "Incomplete type is not allowed error")

    • The reason why I do not like this is because it wastes memory. Meaning if I do not use the class it will just use the memory without actually needing to. The other reason is if you would like to pass an argument to the constructor, this seems impossible using this way.
    • I don't think this is a good long term fix. Please do correct me if I am wrong.

So my question is how to fix this in C++? How can I Synchronize the methods? I understand that in Java Synchronizing these methods lowers the speed of the program by a factor of 100. They use a simple optimizing method but I don't know if it is the same in C++.

I also saw something about the Synchronize attribute but I'm not sure if I understand that correctly.

Aucun commentaire:

Enregistrer un commentaire