mardi 20 décembre 2016

When to use singletons in OOP?

When reading about singletons, I have found this explanation as a reason to use singleton:

since these object methods are not changing the internal class state, we can create this class as a singleton.

What does this really mean ? When you consider that some method is not changing internal class state ? If it is a getter ? Can someone provide code examples for class that uses methods that are not changing its internal state, and therefore can be used as a singleton, and class that should not be a singleton ?

Usually, when people are explaining singleton pattern, they use DB connection class as an example. And that makes sense to me, because I know that I want to have only one db connection during one application instance. But what if I want to provide an option to force using the new connection when I instantiate DB connection class? If I have some setter method, or constructor parameter that forces my class to open new connection, is that class still a subject to be a singleton ?

I am using PHP, but may understand examples written in JAVA, C#...

Aucun commentaire:

Enregistrer un commentaire