c ++: класс регистратора без глобальных объектов или синглтонов или передача его каждому методу

Does anyone knows if it's possible to have a class like a logger without :

  • using a singleton or a global (a la std::cout)

  • passing an instance/pointer/reference to every method which needs it

I take the example of a logger class, but I have a few classes in my application which would benefit from this (for example, the undo manager).

There are several issues with every solution :

  • using a singleton is problematic for testing (along with the many reasons it's generaly not a good idea to use one) . It's the same with a global. Furthermore, nothing guarantees there will be only ONE instance in the application, and it's not even a requirement (why not have 2 loggers for example ?)

  • passing it to every object constructor (dependency injection), leads to a lot of boilerplate code, and can be error prone because you have to copy/paste the same code a lot of times. Can one seriously consider having a pointer to a Logger in every single class' constructor ???????

So I was wondering if there is a third alternative, in C++, I never heard of ? To me it sounds like it would require some black magic under the hood, but I've been pleasantly surprised by some techniques I learned in stack overflow that I couldn't find in google, so I know there are some real gurus here ;)

Surprisingly, I found many discussions about how to design singletons, or why should one not use singletons, but I couldn't find a post addressing my issue...

20
задан Josh Crozier 13 January 2016 в 22:55
поделиться