PHP設計模式學習筆記: 命令模式(Command)

jopen 11年前發布 | 14K 次閱讀 PHP設計模式 PHP開發

// 書本信息操縱類,包括書本的所有操作命令的方法
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())方法, // 就給需要操作的類執行了相應的命令</pre>結果:

開始測試命令模式

創建book之后: Design Patterns by Gamma, Helm, Johnson, and Vlissides

book加星標之后: DesignPatterns by Gamma,Helm,Johnson,and*Vlissides

book去星標之后: Design Patterns by Gamma, Helm, Johnson, and Vlissides

結束測試命令模式</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!