How can I make sure at most one instance of my class is ever created?

John Zukowski

This is an instance where the Singleton design pattern would be used. You need to make the constructor private (so nobody can create an instance) and provide a static method to get the sole instance, where the first time the instance is retrieved it is created:

public class Mine {
  private static Mine singleton;
  private Mine() {
  }
  public static synchronized Mine getInstance() {
    if (singleton == null) {
      singleton = new Mine();
    }
    return singleton;
  }
  // other stuff...
}
For additional information on the Singleton pattern, see the related FAQ entry at http://www.jguru.com/jguru/faq/view.jsp?EID=3434 .
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact