Thursday, March 10, 2011

Implementing Singleton pattern in Java and PHP shows different "static" modifers between Java and PHP

This is a quick note about the difference between Java "static" modifier and PHP "static" modifier. I investigated the different "static" modifiers in Java and PHP (static variable in PHP vs static variable in Java). Here is a quick notes that shows more difference. It is about "synchronized" and multi-threaded safe coding. Java programmer have to pay extra attention when static variables are used. However, this is not problem in PHP. It does not mean PHP is better than Java. It is just because PHP does not natively support multi-thread.

The following are two singleton pattern implementations in Java and PHP respectively. Listing both of them here can clearly show the difference between Java and PHP static variables.

Java Singleton pattern
/**
 * @author Yiyu Jia
 */
public class DBConnectionFactory {
   
    // static means there will be only one instance in one JVM.
    private static DBConnectionFactory m_connFactory = new DBConnectionFactory();

    // private means this class can not be created by "new" operator outside it.
    private DBConnectionFactory() {
        //connManagerList = new ConcurrentHashMap();
    }
    
    public static DBConnectionFactory getInstance() {

        return m_connFactory;

    }


}

To have better understand about Java memory management, singleton pattern, we can refer to this article and links inside it.



PHP singleton pattern
/**
  * @author Yiyu Jia
  */
class JiaLog
{ 
    private static $_instance;   
    private $logger;
    
    // declaring constructor to be private function.
    private function __construct() 
    {       
     $writer = new Zend_Log_Writer_Stream('path/to/logfile');     
     $this->logger = new Zend_Log($writer);     
    }

    //public static function is the way allowed to get instance
    public static function getJiaLog() 
    {
        if (!isset(self::$_instance)) {
            $c = __CLASS__;
            self::$_instance = new $c;
        }
        return self::$_instance;  
    }
    
   
    public function info($str)
    {
        $this->logger->log($str, Zend_Log::INFO);
    }   

    // Prevent users to clone the instance
    public function __clone()
    {
     trigger_error('Clone is not allowed.', E_USER_ERROR);
    }
}

No comments:

Post a Comment