Skip to main content

What is Singleton Pattern?


The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object
Singletons (being often a bad choice) are classes that can have only one instance throughout the whole program.

For example a SingletonConfigFile might look like this.
It is for reading one file only. It would make sense for this to be a config file.
  • If your class can be instantiated more than once, for different files, it is not singleton.
  • Don't use this code - it doesn't take into account concurrency problems which are a whole different area of discussion.
   public SingletonConfigFile {
   private static String filename = "config.xml";
   private File file;
   private static SingletonConfigFile instance;

   private SingletonConfigFile() {
       if (instance != null) {
           throw new Error();
       }
       file = new File(filename);
   }

   public synchronized SingletonConfigFile getInstance() {
      if (instance == null) {
          instance = new SignletonConfigFile();
      }
      return instance
   }

   public String read() {
       // delegate to the underlying java.io.File
   }
}

Comments