The Singleton Design Pattern
- This design pattern is appropriate
- If you want to make sure that you have only one instance of something.
- And you want it universally accessible.
- Why would you want only one instance?
- The Board in a board game.
- A database instance.
- Any resource you only want one of.
- Type 1, the old way
- Much like the handle class, this is achieved through a pointer to the object you only want one of.
- There are some strange ideas in C++ implementation.
- A static method us used to get access to the item.
- If the item is not instantiated, it creates it.
- Otherwise it returns a pointer to the item.
- The constructor is private.
- You need to use the static method to construct an instance of the object.
- You never actually construct an instance of the class.
- The example
- I don't know of a way to destroy the object properly.
- I don't like the fact that I have to pass constructor arguments every time I access an instance of the class.
- You see this pattern picked on all over the place.
- But it has it's uses.
- Type 2, A new way.
- This is attributed to Scott Meyers,
- It is somewhat discussed in your book (p993 +)
- But he does not use templates.
- There is still the problem with passing parameters to the ultimate object constructor.
- The example
- SingletonT2.h
- Instance remains a static method.
- But it holds a static variable.
- Remember, with static variables, they are initialized once when created.
- So this creates an instance of the object on first call.
- Apparently destructors are called on static variables as well.
- So the instance is destroyed when the program exits.
- After that it just returns the stored value.
- A minor shift in the main routine.
- Note that Gregorie does not build a singleton class, he builds his object as a singleton.