Created
April 7, 2021 17:09
-
-
Save gustavoalvesdev/fc1f248a643b0705e222f3829acaf318 to your computer and use it in GitHub Desktop.
Exemplo de Padrão Singleton (PHP)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
class Cliente | |
{ | |
private string $nome; | |
private string $telefone; | |
/* | |
Construtor privado para impedir que a | |
classe seja instanciada sem o uso do | |
método getInstance() | |
*/ | |
private function __construct() {} | |
/* | |
Método responsável por fazer funcionar | |
o uso do padrão Singleton. Ele verifica se | |
já há uma instância do objeto em memória, e | |
caso haja, retorna a instância existente. | |
*/ | |
public static function getInstance() | |
{ | |
static $instance = null; | |
if ($instance === null) { | |
$instance = new Cliente(); | |
} | |
return $instance; | |
} | |
// Métodos acessores (encapsulamento) | |
public function getNome() : string | |
{ | |
return $this->nome; | |
} | |
public function setNome(string $nome) : void | |
{ | |
$this->nome = $nome; | |
} | |
public function getTelefone() : string | |
{ | |
return $this->telefone; | |
} | |
public function setTelefone(string $telefone) : void | |
{ | |
$this->telefone = $telefone; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'Cliente.php'; | |
$cliente1 = Cliente::getInstance(); | |
$cliente1->setNome('Marcos'); | |
print 'NOME DO PRIMEIRO CLIENTE: '.$cliente1->getNome(); | |
$cliente2 = Cliente::getInstance(); | |
// imprimirá o mesmo nome do objeto $cliente1 | |
echo '<br />NOME DO SEGUNDO CLIENTE: '.$cliente2->getNome(); | |
$cliente2->setTelefone('12345'); | |
// imprimirá o mesmo telefone do objeto $cliente2 | |
echo '<br />TELEFONE DO CLIENTE 1: '.$cliente1->getTelefone(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
PADRÃO SINGLETON(Exemplo em PHP)
O padrão Singleton é utilizado quando não podemos ter mais de uma instância de uma mesma classe. Quando criamos um objeto desta classe e queremos garantir que este objeto seja único em todo o sistema.
Neste padrão usamos um construtor privado para evitar que sejam criadas novas instâncias da classe. Para criar a instância ou caso a instância já tenha sido criada, para utilizá-la , criamos o método público e estático getInstance(), além do atributo $instance, privado e estático, que irá guardar a instância criada.
No método getInstance(), nós verificamos se $instance é igual a null. Caso seja, criamos uma instância da classe e armazenamos em $instance. Caso não, retornamos a instância já existente em $instance.