Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 281
Caduchon Avatar asked Mar 26 '26 04:03

Caduchon


1 Answers

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.

like image 120
9Breaker Avatar answered Mar 28 '26 18:03

9Breaker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!