Book a Demo

Author Topic: Problem modeling a singleton class  (Read 3862 times)

EricP

  • EA User
  • **
  • Posts: 122
  • Karma: +0/-0
    • View Profile
Problem modeling a singleton class
« on: September 04, 2009, 04:00:14 am »
Ran into another problem in trying to model a singleton design pattern in EA.

Consider the following singleton class and its implementation:

In the header (.H) file:

class Log
{
  public:
    static Log* Inst(char* filename);
    void Logging(string message);
    void Initialize();
    ~Log();

  protected:
    Log(); // constructor

  private:
    static Log* pInstance;
};


In the .CPP file:

Log* Log::pInstance = NULL;  // <<< note this line

Log* Log::Inst(char* filename)
{
  if(pInstance == NULL)
  {
    pInstance = new Log(filename);
  }
  return pInstance;
}

Log::Log()   // private constructor
{
  // do whatever the constructor needs to do...
}

Log::~Log()
{
  delete pInstance;
  pInstance = NULL;
}


Note that pInstance needs to get declared and initialized outside of any method.  My problem is trying to figure out a way to model this with EA such that when I generate code, the "Log* Log::pInstance = NULL;" gets generated along with the rest of the code... otherwise I get compile errors and have to remember where all those lines of code need to go.

EA version is 7.1.833; if this kind of code generation is provided for in 7.5 let me know and I'll upgrade.

Geert Bellekens

  • EA Guru
  • *****
  • Posts: 13523
  • Karma: +574/-33
  • Make EA work for YOU!
    • View Profile
    • Enterprise Architect Consultant and Value Added Reseller
Re: Problem modeling a singleton class
« Reply #1 on: September 04, 2009, 05:06:19 pm »
I don't really know much abou the EA code generation, but I have modelled the singleton pattern before.
I think you should be creating a static attribute pInstance of type Log with a default value of NULL.
In theory that should result in the code you showed (if I understood your problem/code correctly)

Geert