Powered By Blogger

Wednesday, June 15, 2011

Singleton pattern (Java)

The objective of the singleton pattern is to restrict the instantiation of a class to one object. Following is a simple example of a singleton class;

A singleton class should;
  • Hold private static instance of itself;
  • Have it's constructors to be in private access level.
  • A non-private static method to return the above mentioned instance.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

package com.basic;

import java.util.logging.Logger;

public class Singleton {

    private static Singleton mySingleton = null;
    private static final Logger logger = Logger.getLogger("Singleton");
   
    private Singleton(){
        logger.info("constructor");
    }
   
    public static synchronized Singleton getInstance(){
        logger.info("get instance");
        if(mySingleton == null){
            logger.info("instance null");
            mySingleton = new Singleton();
        }
        return mySingleton;
    }
}

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

The above class cannot be instantiated from any other class since it's constructor is private. Furthermore it holds an instance of itself, which is instantiated in the first call to the method getInstance(). The same instance will be returned to all subsequent calls to the getInstance() method.

thanks,
Shyarmal.

No comments:

Post a Comment