Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Jason Perry   on Feb 11 In Java Category.

  
Question Answered By: Isaac Evans   on Feb 11

The easiest way is to use a static method of the class which uses a
static counter (or flag) variable; the principle goes like this:

1) In your class, declare a static int (or boolean) alreadyCreated.
2) Define a static method which first makes sure that it's called
only once (not twice or more often in parallel executions, that means
you have to execute this method in a single thread always).
3) This method checks whether the flag variable already has been set
to 1 (or greater). If so, it returns null.
4) Otherwise (flag is still 0 or false, depending on the type of the
variable) create a new instance of this class and return it to the
caller _after_ incrementing the counter (or setting the flag to true).

This sort of methods (static methods creating instances of their
class) is called factory methods.

Share: