PHP

invoke在PHP设计模式中的应用案例

小樊
85
2024-07-22 13:18:06
栏目: 编程语言

在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方法被用来执行具体的操作,从而实现了策略模式和命令模式。这样可以灵活的切换不同的策略或命令,而不需要修改调用方的代码。

0
看了该问题的人还看了