Boost logo

Boost :

From: Gennadiy Rozental (rogeeff_at_[hidden])
Date: 2008-01-17 12:06:10


Anthony Williams <anthony_w.geo <at> yahoo.com> writes:

>
> Tobias Schwinger <tschwinger <at> isonews2.com> writes:
>
> >
> > Anthony Williams wrote:
> > > Tobias Schwinger <tschwinger <at> isonews2.com> writes:
> > >> Anthony Williams wrote:
> > >> Having a framework internally use some Singletons can greatly simplify
> > >> its use.
> > >
> > > Possibly, but I don't think they're needed even then. If they're an
> > > implementation detail of the framework, you don't need to make things a
> > > singleton in order to ensure there is only one instance --- just create
one.
> >
> > What's so different between "using a Singleton" and "just creating one"?
>
> A singleton enforces that there is only one global instance with global
> accessibility. If you just create one (and pass it down by dependency
injection)
> then the decision to just create one is made at the top level (where it
> belongs), and the client code doesn't have to be fussed with how many
instances
> there are --- just that it can use the one provided.
>
> void some_function(Logger& logger)
> {
> logger.log("something");
> }
>
> int main()
> {
> Logger myLogger; // ooh look, just one
> some_function(myLogger);
> }

This design has obvios drawback, right: you need to pass the instance around.
Global free function is as bad as global variables IMO and as bad as singlton
for what it worth. Singleton has one advantage - compiler support. If you
working in uncertan environment it might help (and main unscertanty are people
who are using your library), if having multiple instance is actually causing
some inconsistency or allow any other kind of misuse. There are other patterns
that can be used (Monostate for example), but singleton is as simple and
easier to generalize.

Gennadiy


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk