Ubuntu insights, Programming in groovy, java, et als!

Wednesday, June 20, 2012

Design Patterns: Singleton Pattern

* A simple Implementation of a singleton
class MySingleton{
    static MySingleton singletonInstance;
   //****** instantiation ******

    static MySingleton getInstance(){
        if(singletonInstance == null)
            singletonInstance = new MySingleton();
        return singletonInstance;
    private MySingleton(){
        //cannot be called public with new

   //****** logic ******   


FYI, Points to remember

  • Singletons are bad. 
  • They are just glorified statics and hence against OOP principles. 
  • They should be rarely used. A classic example: for logging purposes.
  • Singletons are hard to unit test.
  • Also bad because it is NEVER a good practice to mix instantiation and logic in a single class. 


Post a Comment