mercredi 6 mai 2015

How to design a class that is constant after initialization and exists only once in my whole program

I'm pretty sure that the following question already has a good answer somewhere else, but it's difficult to find since I do not know the "name" of my problem.

I'm designing a class/object/"something" with the following properties:

  • It is sort of a lookup table.
  • It does not chance after initialization
  • It has several non-primitive members.
  • It has a complicated initializer function.
  • It is the same for the whole program.
  • It is parametrized by template parameters.

So this sounds like a static template class:

template <int T>
class LookupTable{

  public:
    static void init(){
      // create entries depending on T
    }

  private:
    static vector<Entries> entries;

}

What I dislike is that I need to call init() somewhere in my program. So the first question is: How can I make this class fully self-contained, with no need to be explicitily initialized somewhere?

Second part: What is the general design approach to implement such a class? I would be perfectly happy with a link to a good example.

I think it's not the singleton pattern, since in the singleton case I can not access entries like LookupTable::getEntry(idx) but would need to use LookupTable::getInstance()->getEntry(idx). It's no big deal but I would be happier with a solution to directly access the static members. Just for more compact and clear notation.

Aucun commentaire:

Enregistrer un commentaire