Saturday, February 12, 2011

Singleton Pattern

Singleton pattern is a kind of creational pattern that deals with the object creation.the intention of the singleton pattern is to limit and control the unnecessary objects creation.therefore it will help to reduce the unnecessary resource usage.singleton pattern ensures that the class has only one instance and it will be globally accessed throughout the application. this pattern can be applied for a situation where the only a single instance of a class is required throughout the application life-cycle.


Singleton Pattern implementation in PHP 

SingletonClass.php


class SingletonClass{


    private static $singletonClassObject = null;

    //  private function __construct() {}

    public static function getSingletonInstance(){

        if(self::$singletonClassObject==null){

            //creating new object
            self::$singletonClassObject = new SingletonClass();

        }

        return self::$singletonClassObject;

    }//getSingletonInstance


}//SingletonClass



the below code represents the client who tries to receive the singleton instance of the above class.


//get the object first time
echo "get the SingletonClass object first time  [".spl_object_hash(SingletonClass::getSingletonInstance())."]<br/>";

//get the object second time
echo "get the SingletonClass object second time [".spl_object_hash(SingletonClass::getSingletonInstance())."]<br/>";



you can see that the both it gets the objects with the same object reference id. that means both invocation leads to get the access for the same object.(not the two different objects). that is why the both time, you get the same object reference.


Singleton Pattern implementation in JAVA

SingletonClass.java
 

public class SingletonClass {

    private static SingletonClass singletonObject = null;


    public static SingletonClass getInstance(){

        if(singletonObject==null){
            //create the object
            singletonObject = new SingletonClass();
        }

        return singletonObject;

    }//getInstance
}//SingletonClass

No comments:

Post a Comment