Detailed explanation of the application of command mode in PHP design pattern_PHP tutorial

WBOY
Release: 2016-07-21 15:10:17
Original
693 people have browsed it

Command mode: Encapsulate a request as an object so that you can parameterize the client with different requests; queue or log requests, and support undoable operations.
Command class:
1. Command role: declares an abstract interface for all specific command classes. This is an abstract role.
2. Specific command role: Define a weak coupling between the acceptor and the behavior; implement the execute method, which is responsible for calling the corresponding operation of the acceptance. The execute() method is usually called the execution method
3. Client role: Create a specific command object and determine its recipient.
4. Requester role: Responsible for calling the command object to execute the request. The related method is called the action method.
5. Acceptor role: Responsible for implementing and executing a request.
Function:
1. Abstract the action to be performed to parameterize the object.
2. Specify, arrange and execute requests at different times.
3. Support cancellation operation
4. Support modification log

Copy code The code is as follows:

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

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

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327127.htmlTechArticleCommand mode: Encapsulate a request as an object, so that you can parameterize the client with different requests; for Request queuing or logging, and support for undoable operations. ...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template