statics inheritance and singletons

  • Thread starter Thread starter Andrew Ducker
  • Start date Start date
A

Andrew Ducker

I'm implementing a singleton using the example at:
http://www.yoda.arachsys.com/csharp/singleton.html
as a basis (second example).

However - I have about 20 classes I wish to make singletons - and I
don't want to duplicate the code in each one. The difficulty comes in
the method that returns the singleton instance. In the example it's:
if (instance == null)
instance = new Class1();
return instance;

But obviously I don't want it to always return Class1 - if I'm calling
Class2 then I want Class2 returned.

Now, I could just put this code into each class, but it seems wasteful
- is there a more efficient way of doing this?

Thanks,

Andy D
 
In a word, no.

If the classes are completely unrelated then you have no choice but to
duplicate the code in each one.

If they belong in a logical hierarchy (that is, some of them have
"is-a" relationships with the other ones, and no, "is a Singleton"
doesn't count) then you can create a "cheat" singleton that has a
protected constructor rather than a private one. This will allow for
"singleton inheritance", which isn't really singleton any more, but
hey, rules are made to be broken.

For example, one case I can think of for singleton inheritance is if
you want to create a "unit test" version of a class that inherits from
the production version (something in a data layer, for example, which
for test purposes must parrot back canned test data rather than
connecting to a database).

Inheritance doesn't help you at all with the Singleton pattern itself,
because all of the code that implements Singleton is static, and so
doesn't participate in inheritance.
 
Andrew Ducker said:
I'm implementing a singleton using the example at:
http://www.yoda.arachsys.com/csharp/singleton.html
as a basis (second example).

However - I have about 20 classes I wish to make singletons - and I
don't want to duplicate the code in each one. The difficulty comes in
the method that returns the singleton instance. In the example it's:
if (instance == null)
instance = new Class1();
return instance;

But obviously I don't want it to always return Class1 - if I'm calling
Class2 then I want Class2 returned.

Now, I could just put this code into each class, but it seems wasteful
- is there a more efficient way of doing this?

I'm afraid there isn't - but it's a lot easier if you use the version
which is just:

public static readonly Class1 Instance = new Class1();

Then it's just that line which is duplicated in each class.
 
Back
Top