Memento - Design Pattern
Hoje eu estava estudando o pattern Memento e pelo o que eu entendi ele é como um rollback (me corrijam se eu estiver errado).
Pelo o que eu estudei, criei isso, para arquivos. Gostaria de saber se apliquei o pattern corretamente.
class Memento{
private $storage;
public function __construct( $storage ){
$this->storage = $storage;
}
public function get(){
return $this->storage;
}
}
class CareTaker{
private $texts;
public function __construct(){
$this->texts = array();
}
public function add( Memento $text ){
$this->texts[] = $text;
}
public function getUltimateState(){
if( count( $this->texts ) <= 0 ){
return null;
}
$ultimateState = $this->texts[ count( $this->texts ) - 1 ];
unset( $this->texts[ count( $this->texts ) - 1 ] );
return $ultimateState;
}
}
class FileEditor{
private $file;
private $fileContent;
private $caretaker;
public function __construct( $file ){
$this->file = $file;
$fopen = fopen( $file, 'r' );
$this->fileContent = fgets( $fopen, 1024 );
fclose( $fopen );
$this->caretaker = new CareTaker;
}
public function addContent( $content ){
$content = file_get_contents( $this->file );
$memento = new Memento( $content );
$this->caretaker->add( $memento );
$fopen = fopen( $this->file, 'a+' );
$fwrite = fwrite( $fopen, $content );
fclose( $fopen );
$this->fileContent = file_get_contents( $this->file );
}
public function undoContent(){
$fopen = fopen( $this->file, 'w' );
$fwrite = fwrite( $fopen, $this->caretaker->getUltimateState()->get() );
fclose( $fopen );
}
public function getContent(){
return $this->fileContent;
}
}
$editor = new FileEditor( 'file-txt.txt' );
$editor->addContent( 'Esse código' );
$editor->addContent( ' foi escrito' );
$editor->addContent( ' numa IDE' );
$editor->undoContent();Discussão (3)
Carregando comentários...