Was this helpful?
2 votes
|
The Singleton design pattern is one of the original Gang of Four design patterns. It is designed to limit the number of instances of a class to just one. When would you want to use this? In fact, the scenario is quite common. Suppose you have a class, we'll call it Not using a Singleton in the above scenario could lead to duplicate trackers and all kinds of wrong information. Here is an example of the simplest possible Singleton class:
Notice the class maintains a reference to itself with the static Next notice the private constructor. This prevents anyone from creating an instance of
The only way to access this class in the application is with the following code:
This class demonstrates another pattern: the Lazy Load pattern. The instance is only created when it is really needed. You can see how this works in this block:
Finally, here is a simple example of the
|
posted | Apr 01, 2016 |
viewed | 602 times |
active | Apr 06, 2016 |