@blog.justoneplanet.info

日々勉強

Command Pattern

■コード

File.php

class File {
    private $name;
    public function __construct($name) {
        $this->name = $name;
    }
    public function decompress() {
        // 
    }
    public function compress() {
        //
    }
    public function create() {
        //
    }
}

Command.php

interface Command {
    public function execute();
}

TouchCommand.php

class TouchCommand implements Command {
    private $file;
    public function __construct(File $file) {
        $this->file = $file;
    }
    public function execute() {
        $this->file->create();
    }
}

CompressCommand.php

class CompressCommand implements Command {
    private $file;
    public function __construct(File $file) {
        $this->file = $file;
    }
    public function execute() {
        $this->file->compress();
    }
}

CopyCommand.php

class CopyCommand implements Command {
    private $file;
    public function __construct(File $file) {
        $this->file = $file;
    }
    public function execute() {
        $file = new File('copy_' . $this->file->getName());
        $file->create();
    }
}

Queue.php

class Queue {
    private $commands;
    private $currentIndex;
    public function __construct() {
        $this->commands = array();
        $this->currenrIndex = 0;
    }
    public function addCommand(Command $command) {
        $this->commands[] = $command;
    }
    public function run() {
        while(!is_null($command = $this->next())) {
            $command->execute();
        }
    }
    private function execute() {
        if(count($this->commands) === 0 || count($this->commands) <= $this->currentIndex) {
            return null;
        }
        else {
            return $this->commands[$this->currentIndex++];
        }
    }
}

■クライアントコード

$queue = new Queue();
$file = new File('hoge.txt');
$queue->addCommand(new TouchCommand($file));
$queue->addCommand(new CompressCommand($file));
$queue->addCommand(new CopyCommand($file));
$queue->run();

コメントはまだありません»

No comments yet.

RSS feed for comments on this post.TrackBack URL

Leave a comment