CaptainHastings
CaptainHastings

Reputation: 1597

Singletons or non-singletons wrapped by a Singleton

I have a singleton class called SingletonController1.

This SingletonController1 instantiates a bunch of others Singleton classes.

SingletonController1{
Authenticator - Singleton;
DBAccessor - Singleton;
RiskAccessor - Singleton;
}

My question is, what if I rework this design to:

   SingletonController2{
    Authenticator -non-singleton;
    DBAccessor -non-singleton;
    RiskAccessor -non-singleton;
    }

As long as SingletonController2 is the only class that instantiates those three non-Singleton classes, wouldn't this be functionally the same as the previous design?

Cheers

Upvotes: 4

Views: 520

Answers (4)

ZeroPhase
ZeroPhase

Reputation: 647

Lately, what I've been doing is using dependency injection frameworks for the creation of objects. What they can do is make a class into a singleton with a line of code that configures how that class is created. That way if you ever need more than one of an object, you just delete the line and change the architecture for calling it slightly. I've just used a framework built to work with Unity 3D, so I don't know for certain if the frameworks outside of Unity 3D support this, but I have a good feeling they do.

Upvotes: 0

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

I think you are on the right track, but push it further. Go right back to your root of your program and you only need one singleton. There's a logical step after that too.

Upvotes: 1

quosoo
quosoo

Reputation: 829

Functionality will be the same, but flexibility much greater in the second case as the non-singleton classes can be reused elsewhere in your application/system. If they don't need to be singletons let they not be singletons.

Upvotes: 5

Asaph
Asaph

Reputation: 162801

Yes. These 2 designs accomplish the same thing, given your condition that no class other than Singleton2 instantiates Authenticator, DBAccessor and RiskAccessor.

Upvotes: 1

Related Questions