mercredi 30 octobre 2019

How to replace singleton design pattern

I have my own simple Timer implementation, when a timer is created it register itself at a TimerHandler,

Timer::Timer()
: tick_counter_(0),
  target_tick_(0),
  increment_(false),
  started_(false),
  elapsed_(false) {
  handlers::TimerHandler::RegisterTimer(*this);
}

The function RegisterTimer() is static as you can see and TimerHandler is implemented as a singleton.

As you all known this creates problems at unit testing! Testing the Timer class and the TimerHandler class can be ok and not really hard. But when testing other classes which uses Timer it sometimes become tricky.

I want to get some ideas of how to solve this problem using another kind of design.

My only solution I have come up with currently is to use simple dependency injection by simply passing TimerHandleras an argument everywhere I want to use a Timer. But this will clutter my code badly so I hope to be able to avoid this!

Aucun commentaire:

Enregistrer un commentaire