I am a little bit confused about simple factory and factory method. My main difficult is the abrut difference between the examples code on the internet, even on wikipedia, where have lots of them, some with Interfaces, some with Switch cases and some even with registers
I've create this simple one example, using PHP, but I'am not confident if its can be considered a simple factory and/or factory method:
<?php
abstract class Log {
protected $nome;
public function __construct(string $nome) {
touch($nome);
$this->nome = $nome;
}
protected function getDataHora(): string {
return (new \DateTime())->format('Y-m-d h:I:s.v');
}
public abstract function insert(string $texto);
public abstract function read(): string;
}
class TextLog extends Log {
public function insert(string $texto) {
$log_entry = $this->getDataHora() . ";" . $texto . PHP_EOL;
file_put_contents($this->nome, $log_entry, FILE_APPEND | LOCK_EX);
}
public function read(): string {
return file_get_contents($this->nome);
}
}
class JsonLog extends Log {
public function insert(string $texto) {
$log_entry = ['data' => $this->getDataHora(), 'texto' => $texto];
$json = file_get_contents($this->nome);
$tempArray = json_decode($json, true);
if(!is_array($tempArray)){
$tempArray = [];
}
array_push($tempArray, $log_entry);
$jsonData = json_encode($tempArray);
file_put_contents($this->nome, $jsonData);
}
public function read(): string {
$json = file_get_contents($this->nome);
$array = json_decode($json);
return implode(";", $array);
}
}
class LogFactory {
public static function get(string $tipo): Log {
switch (strtoupper($tipo)) {
default:
case 'TXT':
return new TextLog("log.txt");
case 'JSON':
return new JsonLog("log.json");
}
}
}
$log = LogFactory::get('txt');
var_dump($log);
$log->insert('Testando 1,2,3...');