Quantcast
Viewing all articles
Browse latest Browse all 11

Answer by Telastyn for Alternatives to the singleton pattern

Your original requirements:

So the general my scenario is that

  1. I need only one instance of a class either for optimization reasons (I do not need >multiple factory objects) or for sharing common state (e.g. the factory knows how many >instances of A it can still create)
  2. I need a way to have access to this instance f of F in different places of the code.

Do not line up with the definition of a singleton (and what you rather refer to later). From GoF (my version is 1995) page 127:

Ensure a class only has one instance, and provide a global point of access to it.

If you only need one instance, that does not preclude you from making more.

If you want a single, globally accessible instance then make a single globally accessible instance. There is no need to have a pattern named for everything you do. And yes, single globally accessible instances are usually bad. Giving them a name doesn't make them less bad.

To avoid global accessibility, the common 'make an instance and pass it along' or 'have the owner of two objects glue them together' approaches work well.


Viewing all articles
Browse latest Browse all 11

Trending Articles