Ver Mensaje Individual
  #1 (permalink)  
Antiguo 19/07/2011, 09:40
Avatar de Italico76
Italico76
 
Fecha de Ingreso: abril-2007
Mensajes: 3.303
Antigüedad: 17 años
Puntos: 292
Singleton: implementacion

He visto innumerables implementaciones de Singleton...todas diferentes...

Código PHP:
Class Singleton {

  
/* 
    Primero se crea la instancia y se imprime 'Hey',
  e inmediatamente luego se ejecuta el constructor,
  imprimiendose ' boy!'
  */
  
public function __construct(){
    echo 
' boy!';
  }

  static function 
arranque(){
    static 
$instancia 0;  
  
   
// podria haber chequeado: !is_object($instancia)
    
if (!($instancia instanceof singleton)){
      echo 
'Hey';
      
$instancia = new singleton;
    }    
  }  

#

/* Imprime SOLO UNA VEZ: Hey boy */
$x singleton :: arranque();
$x singleton :: arranque();
$x singleton :: arranque(); 
La de arriba es mia...pero aca otra... por ejemplo:

Código PHP:
<?
class Database 

    
// Store the single instance of Database 
    
private static $m_pInstance

    private function 
__construct() { 
      echo 
'Test ..';
    } 

    public static function 
getInstance() 
    { 
        if (!
self::$m_pInstance
        { 
            
self::$m_pInstance = new Database(); 
        } 

        return 
self::$m_pInstance
    } 
}
Mi duda: la puedo hace de CUALQUIER forma ? (mas alla de evitar clonacion del objeto, etc) o hay ventajas ? GRACIAS!
__________________
Salu2!