state = $state;
}
public function getState(): string
{
return $this->state;
}
}
// ====================== ORIGINATOR ======================
class TextEditor
{
private string $text = '';
public function write(string $newText): void
{
$this->text .= $newText;
}
public function getText(): string
{
return $this->text;
}
// Crea un memento con el estado actual
public function save(): Memento
{
return new Memento($this->text);
}
// Restaura el estado desde un memento
public function restore(Memento $memento): void
{
$this->text = $memento->getState();
}
}
// ====================== CARETAKER ======================
class History
{
/** @var Memento[] */
private array $history = [];
public function save(Memento $memento): void
{
$this->history[] = $memento;
}
public function undo(): ?Memento
{
if (empty($this->history)) {
return null;
}
return array_pop($this->history);
}
}
// ====================== USO ======================
$editor = new TextEditor();
$history = new History();
echo "=== Editor de Texto - Patrón Memento ===\n\n";
// Primera versión
$editor->write("Hola mundo.\n");
$history->save($editor->save());
echo "Versión 1: " . $editor->getText() . "\n";
// Segunda versión
$editor->write("Esto es una prueba.\n");
$history->save($editor->save());
echo "Versión 2: " . $editor->getText() . "\n";
// Tercera versión
$editor->write("Agregando más contenido...");
echo "Versión 3: " . $editor->getText() . "\n\n";
// === Deshacer ===
echo "Deshaciendo...\n";
$editor->restore($history->undo());
echo "Después de undo: " . $editor->getText() . "\n";
$editor->restore($history->undo());
echo "Después de segundo undo: " . $editor->getText() . "\n";
Salida esperada: