Technology with opinion

Thursday, April 15, 2010

Generic Singleton Factory

Not too long after writing and blogging about a generic singleton base, I changed the code to use a Factory - a singleton factory to be specific. Below is a factory which can be used to create a singleton instance of any class. The original singleton base class implementors needed to be sealed or have unintended consequences of getting an instance of the wrong class. This caused me to reflect and conclude that the design was deceptive as it was almost in essense a factory.

Below is a refactored version which is a little more genuine. This is my first crack, and requires generics. I do not use this everywhere I use singletons but where the usage of a Factory fits better than a singleton such as when you have many implementors of the same interface and you want singleton creational behavior.

Jon Skeet's has a great article on some different singleton designs in his blog.

1 comment:

larva said...

thank you