Introduction
I wanted to have my own and simple handling for the singleton design pattern without implementing it many times. Singleton is an object-based creation pattern. You should implement it to ensure that only one instance of a class exists to have a global access point.
I often used the singleton design pattern to hold the settings of a configuration file. However, I had to implement the pattern every time and sometimes I had to write a method for initializing some variables of the instance, as well as implement a check to watch for instance initialization. I needed a quick and simple way to use the singleton design pattern... And here comes my approach to solving this.
Using the Code
I delegated creation and initialization of the singleton class instance to a generic builder class called UZi.Singleton.SingletonBuilder<T>. See more details in my source code. You can (and should) check the arguments for the constructor of your singleton class with the delegate UZi.Singleton.SingletonClassConstructorArgsChecker. Now you can write code like this, if x is a defined class:
x singletonInstanceOfX = UZi.Singleton.Singleton<x>,
UZi.Singleton.SingletonBuilder<x>.GetInstance(
UZi.Singleton.SingletonClassConstructorArgsChecker
)someMethodToCheckArgsForTheSingletonClassCtor,
new object[] { 1, "string_value" });
You can now use singletonInstanceOfX everywhere in your application and you only ever have this one instance of x. Don't forget to make the constructor of your class, which should be a singleton class, private or protected!
Points of Interest
With my approach, you can simply use the singleton design pattern. You'll never have to implement it for a class serving as a singleton instance. We also never have to implement a builder class to build an initialized instance of our singleton class. Use the generic code and save time.
History
- 2007-09-12: First version
- 2007-09-12: Tried to fix some formatting mistakes