jeudi 24 août 2023

Why do singletons use a function that returns an object instead of a simple initializing function?

On this site and others, I always see singletons written like this:

<?php

Class Singleton {
    private static $code = null;
    private static $instance = null;
    
    private function __construct() {
        self::$code = 'some_expensive_operation';
    }
    
    public static function getInstance() {
        if ( is_null(self::$instance) ) {
            self::$instance = new Singleton();
        }
     
        return self::$instance;
    }
    
    public static function useCode() {
        echo self::$code;
    }
}

// to use
$object1 = Singleton::getInstance();
$object1::useCode();

?>

But wouldn't it make more sense to write them like this, with a regular initializing function instead of a constructor?

<?php

Class Singleton {
    private static $code = null;
    
    public static function initialize() {
        if ( is_null(self::$code) ) {
            self::$code = 'some_expensive_operation';
        }
    }
    
    public static function useCode() {
        echo self::$code;
    }
}

Singleton::initialize();

// to use
Singleton::useCode();

?>

I'm drawn to the second example because using it only requires one line and no throwaway variable. It seems much cleaner.

Aucun commentaire:

Enregistrer un commentaire