ffenix
ffenix

Reputation: 553

about singleton

Well i read singleton are bad because they are anti pattern. I also read that the main reason for this is the global reference to singleton, anyway:

is it always possible to avoid singleton?

If so, lets says for example i got an IOCP network and i need to initialize it once and this object needs to be constant through the entire lifetime of the software. Same comes with a class i have called "paint" where i print data into the screen. If i didn't make a singleton of it i would still need a global variable of the current Hwnd and to initialize the object locally each time i am going to use it (really annoying).

So using singleton is a sign my design is flaw? What can i do to avoid them?

Thanks.

Upvotes: 2

Views: 143

Answers (2)

Brady
Brady

Reputation: 10357

Its a question of which entities need access to the resource that can only be instantiated once, and when (henceforth called the resource).

If the entities that need access to this resource can be instantiated with the resource (IOC, dependency injection), then that is the best way to go, thus keeping things simple and avoiding creating a Singleton. KISS.

If, for some reason, there are entities that need access to the resource, but cant be instantiated with it, then an alternative needs to be implemented. One option is a Singleton, but another option that I like to use is a Factory. This completely encapsulates the creation of the resource, and is much more future-proof, meaning that if in the future for some reason, more than one instance of the resource can be instantiated, then its all encapsulated. You cant/shouldnt try to do this with a Singleton. Of course, internally the factory will maintain the unique instance of the resource.

There are those that would argue that if an entity cant be instantiated with the resource, then the design is bad. That can be argued, and should probably be done so an a case-by-case basis.

Upvotes: 0

BЈовић
BЈовић

Reputation: 64283

is it always possible to avoid singleton?

Yes, use a global variable, or (even better) fix your design. One option to fix a design is to use some kind of inversion of control.

If you try to use OO principles, you'll see you can do without a singleton.

Upvotes: 5

Related Questions