简体   繁体   中英

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

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.

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM