Caduchon
Caduchon

Reputation: 5231

Access to singleton with static functions

Consider I have a singleton class Foo. The question here is not about the way to implement the singleton idiom, then I don't explicit it. I have somthing like that:

class Foo
{
  private:
          Foo();
          ~Foo();
  public:
    void  doSomething();
    int   getSomething() const;
  public:
    static Foo&  getInstance();
};

Then, in my mind, the classical way to call it is the following:

Foo::getInstance().doSomething();
int i = Foo::getInstance().getSomething();

It's quite annoying to always have to write Foo::getInstance() to access the instance and execute the expected task. Then my question is the following: what about duplicate functions as static functions, keeping the singleton mechanic, but making access shorter ?

class Foo
{
  private:
          Foo();
          ~Foo();
  public:
    void  doSomething();
    int   getSomething() const;
  public:
    static Foo&  getInstance();
    static void  _doSomething() { Foo::getInstance().doSomething(); }
    static int   _getSomething() { return Foo::getInstance().getSomething(); }
};

And then, I can call it with this shorter version:

Foo::_doSomething();
int i = Foo::_getSomething();

Is it common ? Is there good reasons to not do that (and why) ? Is there other (better) ways to simplify calls to singleton classes ?

Note: I don't use C++11 for compatibility reason.

Upvotes: 4

Views: 1219

Answers (1)

9Breaker
9Breaker

Reputation: 724

There is nothing wrong with the other static methods that make it shorter to call the other methods of your singleton.

If another class is frequently calling the singleton's methods, then consider a private member reference to the singleton in the other class that will get set upon construction of that class (assuming your singleton has been constructed before the other object's construction).

class Bar{

private:
    Foo& fooRef;
    void doA();


public:
    Bar();
    ~Bar();
};

And then in the constructor:

Bar() :
    fooRef(Foo::getInstance())
{}

And now for ease of use in Bar::doA() you can call:

void Bar::doA(){
    fooRef.doSomething(); 
}

And I know you said your question was not about singleton implementation, but I thought I would throw this in and say don't forget to prevent copy construction and assignment for the singleton.

Upvotes: 1

Related Questions