在PHP設計模式中,invoke方法通常用于實現“策略模式”和“命令模式”。
在“策略模式”中,invoke方法可以用來執行不同的策略類。例如:
interface PaymentStrategy {
public function invoke();
}
class CreditCardPayment implements PaymentStrategy {
public function invoke() {
echo "Processing credit card payment...";
}
}
class PayPalPayment implements PaymentStrategy {
public function invoke() {
echo "Processing PayPal payment...";
}
}
class PaymentContext {
private $paymentStrategy;
public function __construct(PaymentStrategy $paymentStrategy) {
$this->paymentStrategy = $paymentStrategy;
}
public function processPayment() {
$this->paymentStrategy->invoke();
}
}
$creditCardPayment = new CreditCardPayment();
$paymentContext = new PaymentContext($creditCardPayment);
$paymentContext->processPayment(); // Output: Processing credit card payment...
在“命令模式”中,invoke方法可以用來執行具體的命令操作。例如:
interface Command {
public function invoke();
}
class Light {
public function turnOn() {
echo "Light turned on";
}
public function turnOff() {
echo "Light turned off";
}
}
class TurnOnLightCommand implements Command {
private $light;
public function __construct(Light $light) {
$this->light = $light;
}
public function invoke() {
$this->light->turnOn();
}
}
class TurnOffLightCommand implements Command {
private $light;
public function __construct(Light $light) {
$this->light = $light;
}
public function invoke() {
$this->light->turnOff();
}
}
class RemoteControl {
private $command;
public function setCommand(Command $command) {
$this->command = $command;
}
public function pressButton() {
$this->command->invoke();
}
}
$light = new Light();
$turnOnCommand = new TurnOnLightCommand($light);
$turnOffCommand = new TurnOffLightCommand($light);
$remote = new RemoteControl();
$remote->setCommand($turnOnCommand);
$remote->pressButton(); // Output: Light turned on
$remote->setCommand($turnOffCommand);
$remote->pressButton(); // Output: Light turned off
在這兩個案例中,invoke方法被用來執行具體的操作,從而實現了策略模式和命令模式。這樣可以靈活的切換不同的策略或命令,而不需要修改調用方的代碼。