lundi 25 avril 2016

Design pattern to use when you need to initialize your object?

I have a class, which has an Initialize method, which creates a bunch of tables in a database. This class looks like this:

public class MyClass
{
  private bool initialized = false;

  public void Initialize()
  {
    if(!initialized)
    {
        //Install Database tables
        initialized = true;
    }
  }

  public void DoSomething()
  {
    //Some code which depends on the database tables being created 
  }

  public void DoSomethingElse()
  {
    //Some other code which depends on the database tables being created 
  }
} 

The two methods DoSomething and DoSomethingElse need to make sure that the Initialize method has been called before proceeding because they depend on having the tables in the database. I have two choices:

  1. Call the Initialize method in the constructor of the class - this does not seem like a good idea because constructors should now call methods, which are non-trivial and could cause an exception.

  2. Call the Initialize method in each of the two methods - this does not seem like a great solution either especially if there are more than a handful of methods.

Is there a design pattern which could solve this in a more elegant way?

Aucun commentaire:

Enregistrer un commentaire