Created
July 28, 2018 06:00
-
-
Save bz0/9528c74ee0c9693ff05cf7faed291bae to your computer and use it in GitHub Desktop.
GoF Commandパターン
This file contains 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 | |
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