Example use of command mode for php design pattern

  • 2021-01-18 06:21:29
  • OfStack

Command:
1. Command role: Declares an abstract interface for all concrete command classes. This is an abstract role.
2. Specific command roles: define the weak coupling between a receiver and the behavior; Implement the execute method, which is responsible for invoking the accepted corresponding operation. The execute() method is often called an execution method
3. Customer role: Create a concrete command object and identify its recipient.
4. Requestor role: responsible for invoking the command object to execute the request, the related methods are called action methods.
5. Recipient role: responsible for implementing and executing 1 request.
Function:
1. Parameterize the object by abstracting the actions to be executed.
2. Specify, sequence, and execute requests at different times.
3. Support cancel operation
4. Support change log


<?php
// The command interface 
interface Command{
     public function execute();
}
// Specific commands 
class ConcreteCommand implements Command{
     private $_receiver;
     public function __construct($receiver){
          $this->_receiver = $receiver;
     }
     public function execute(){
          $this->_receiver->action();
     }
}

// The recipient 
class Receiver{
     private $_name;
     public function __construct($name){
          $this->_name = $name;
     }
     // Action method 
     public function action(){
          echo $this->_name.'do action .<br/>';
     }
}
// The requester 
class Invoker{
     private $_command;
     public function __construct($command){
          $this->_command = $command;
     }
     public function action(){
          $this->_command->execute();
     }
}

// The client 
class  Client{
     public static function main(){
          $receiver = new Receiver('jaky');
          $command = new ConcreteeCommand($receiver);
          $invoker = new Invoker($command);
          $invoker->action();
     }
}
Client::main();
?>


Related articles: