// 书本信息操纵类,包括书本的所有操作命令的方法class BookCommandee { private $author; private $title; function __construct($title_in, $author_in) { $this->setAuthor($author_in); $this->setTitle($title_in); } function getAuthor() { return $this->author; } function setAuthor($author_in) { $this->author = $author_in; } function getTitle() { return $this->title; } function setTitle($title_in) { $this->title = $title_in; } function setStarsOn() { $this->setAuthor(str_replace(' ','*',$this->getAuthor())); $this->setTitle(str_replace(' ','*',$this->getTitle())); } function setStarsOff() { $this->setAuthor(str_replace('*',' ',$this->getAuthor())); $this->setTitle(str_replace('*',' ',$this->getTitle())); } function getAuthorAndTitle() { return $this->getTitle().' by '.$this->getAuthor(); }}// 抽象类,规定必须有书本操纵类属性和exexute()方法abstract class BookCommand { protected $bookCommandee; function __construct($bookCommandee_in) { $this->bookCommandee = $bookCommandee_in; } abstract function execute();}// 继承自BookCommand抽象类的专门加星标的类class BookStarsOnCommand extends BookCommand { function execute() { $this->bookCommandee->setStarsOn(); }}// 继承自BookCommand抽象类的专门去星标的类class BookStarsOffCommand extends BookCommand { function execute() { $this->bookCommandee->setStarsOff(); }} writeln('开始测试命令模式'); writeln(''); // 创建一个书本操纵类 $book = new BookCommandee('Design Patterns', 'Gamma, Helm, Johnson, and Vlissides'); // 可以用这个类得到它的书名等属性 writeln('创建book之后: '); writeln($book->getAuthorAndTitle()); writeln(''); // 创建一个专门加星标的类 // 调用它的execute()方法,给书本加星标 $starsOn = new BookStarsOnCommand($book); callCommand($starsOn); writeln('book加星标之后: '); writeln($book->getAuthorAndTitle()); writeln(''); // 创建一个专门去星标的类 // 调用它的execute()方法,给书本去星标 $starsOff = new BookStarsOffCommand($book); callCommand($starsOff); writeln('book去星标之后: '); writeln($book->getAuthorAndTitle()); writeln(''); writeln('结束测试命令模式'); function callCommand(BookCommand $bookCommand_in) { $bookCommand_in->execute(); } function writeln($line_in) { echo $line_in.PHP_EOL; }// 我想这个精髓就是,把针对某个类的操作命令,全部放在一个专门的类里面去,调用这个专门的命令类的执行(execute())方法,// 就给需要操作的类执行了相应的命令
结果:
开始测试命令模式创建book之后: Design Patterns by Gamma, Helm, Johnson, and Vlissidesbook加星标之后: Design*Patterns by Gamma,*Helm,*Johnson,*and*Vlissidesbook去星标之后: Design Patterns by Gamma, Helm, Johnson, and Vlissides结束测试命令模式