Listo (Ctrl + Enter para ejecutar) Bootcamp Fullstack »
ejemplo.php
Tab = 4 espacios
1
<?php
declare(strict_types=1);

// ==========================================
// 1. PATRÓN SINGLETON (Instancia Única)
// ==========================================
final class ConexionConfig
{
    private static ?self $instancia = null;
    private string $idSesion;

    // Constructor privado: Impide usar 'new ConexionConfig()' desde fuera
    private function __construct()
    {
        $this->idSesion = bin2hex(random_bytes(4)); // ID aleatorio único
    }

    // Método de acceso global
    public static function getInstancia(): self
    {
        if (self::$instancia === null) {
            self::$instancia = new self();
        }
        return self::$instancia;
    }

    public function getId(): string
    {
        return $this->idSesion;
    }

    // Prohibir clonación y deserialización
    private function __clone() {}
}

// ==========================================
// 2. PATRÓN FACTORY (Factoría de Objetos)
// ==========================================
interface TransporteInterface
{
    public function entregar(): string;
}

final class CamionTransporte implements TransporteInterface
{
    public function entregar(): string
    {
        return "🚚 Entrega terrestre por camión de carga.";
    }
}

final class BarcoTransporte implements TransporteInterface
{
    public function entregar(): string
    {
        return " Cargo marítimo internacional en contenedor.";
    }
}

final class TransporteFactory
{
    public static function crear(string $tipo): TransporteInterface
    {
        return match(strtolower($tipo)) {
            'terrestre' => new CamionTransporte(),
            'maritimo'  => new BarcoTransporte(),
            default     => throw new InvalidArgumentException("Tipo de transporte no soportado: {$tipo}")
        };
    }
}

// ==========================================
// PRUEBA EN EL SANDBOX
// ==========================================
echo "<h2>1. Prueba del Patrón Singleton:</h2>";
$config1 = ConexionConfig::getInstancia();
$config2 = ConexionConfig::getInstancia();

echo "<p>ID Sesión Configuración 1: <strong>#{$config1->getId()}</strong></p>";
echo "<p>ID Sesión Configuración 2: <strong>#{$config2->getId()}</strong></p>";

if ($config1 === $config2) {
    echo "<p style='color:#10b981; font-weight:bold;'>✔ Ambas variables apuntan a la EXACTA misma instancia en memoria RAM.</p>";
}

echo "<hr><h2>2. Prueba del Patrón Factory:</h2>";
$envioA = TransporteFactory::crear('terrestre');
$envioB = TransporteFactory::crear('maritimo');

echo "<p>" . $envioA->entregar() . "</p>";
echo "<p>" . $envioB->entregar() . "</p>";
Haz clic para editar este código
Vista Previa
Servidor PHP 8.3