Thursday, November 28, 2013

Singleton Design Pattern

Singleton is a simple design pattern.  It is used when you want one global object that can be used throughout the entire project. An example when you may want to do this is when using debug tools like a logger. You would only like one logger in your project so that one logger is logging your projects information out to the same file, so you do not end up with multiple files.
In order to have one instance of the object you need to control when the object gets initialized. One way to do this is to do the initialization of the class in itself and to disallow the any coping or assignment of the class. So first you make the constructor private and disallow copy and assignment.  The reason for disallowing copy and assignment is so we do not let ourselves or anybody else to make another instance of the object.  You should end open with something like this:

             




            

                Next you need to declare your instance of the class, so declare a static instance of the class as private. Now we need a way to give access of that instance to other classes. So make a public static function that return an address of the class. Next define the function so it returns the static instance that you just declared.  Now to call the single instance of the object in another class you scope into the class and call the function that returns the class like so, “YourClass::GetTheInstance()”. And that all this is to the Singleton design pattern.
 

No comments:

Post a Comment