Skip to content

Instantly share code, notes, and snippets.

@bz0
Created July 28, 2018 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bz0/9528c74ee0c9693ff05cf7faed291bae to your computer and use it in GitHub Desktop.
Save bz0/9528c74ee0c9693ff05cf7faed291bae to your computer and use it in GitHub Desktop.
GoF Commandパターン
<?php
class File {
private $name;
public function __construct($name){
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function decompress() {
echo $this->name . "を展開しました<br>";
}
public function compress() {
echo $this->name . "を圧縮しました<br>";
}
public function create() {
echo $this->name . "を作成しました<br>";
}
}
interface Command{
public function execute();
}
class TouchCommand implements Command {
private $file;
public function __construct(File $file){
$this->file = $file;
}
public function execute(){
$this->file->create();
}
}
class CompressCommand implements Command {
private $file;
public function __construct(File $file){
$this->file = $file;
}
public function execute(){
$this->file->compress();
}
}
class CopyCommand implements Command {
private $file;
public function __construct(File $file){
$this->file = $file;
}
public function execute(){
$file = new File('copy_of_' . $this->file->getName());
$file->create();
}
}
class Queue {
private $commands;
private $current_index;
public function __construct(){
$this->commands = array();
$this->current_index = 0;
}
public function addCommand(Command $command){
$this->commands[] = $command;
}
public function run(){
while (!is_null($command = $this->next())){
$command->execute();
}
}
public function next(){
if (count($this->commands) === 0 ||
count($this->commands) <= $this->current_index) {
return null;
}else{
return $this->commands[$this->current_index++];
}
}
}
$queue = new Queue();
$file = new File("sample.txt");
$queue->addCommand(new TouchCommand($file));
$queue->addCommand(new CompressCommand($file));
$queue->addCommand(new CopyCommand($file));
$queue->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment