php command mode (command pattern)

...

<?php
/*
The command pattern decouples the object that executes certain operations from
objects that know how to use it. It does so by encapsulating all of the relevant
information needed for later execution of a certain action. This implies information
about object, method name, and method parameters.
*/

interface LightBulbCommand {
    public function execute();
}

class LightBulbControl {
    public function turnOn() {
        echo 'LightBuld turnOn.<br/>';
    }
    
    public function turnOff() {
        echo 'LightBuld turnOff.<br/>';
    }
}

class TurnOnLightBulb implements LightBulbCommand {
    private $lightBulbControl;
    
    public function __construct(LightBulbControl 
        $lightBulbControl) {
            $this->lightBulbControl = $lightBulbControl;
        }
        
    public function execute() {
        $this->lightBulbControl->turnOn();
    }
}

class TurnOffLightBulb implements LightBulbCommand {
    private $lightBulbControl;
    
    public function __construct(LightBulbControl 
        $lightBulbControl) {
            $this->lightBulbControl = $lightBulbControl;
        }
        
    public function execute() {
        $this->lightBulbControl->turnOff();
    }
}

$command = new TurnOffLightBulb(new LightBulbControl());
$command->execute();

$command = new TurnOnLightBulb(new LightBulbControl());
$command->execute();
?>

Guess you like

Origin www.cnblogs.com/aguncn/p/11184349.html