。。。

<?php
/*
The strategy pattern defines a family of algorithms, each of which is encapsulated
and made interchangeable with other members within that family.
*/

interface PaymentStrategy {
    public function pay($amount);
}

class StripePayment implements PaymentStrategy {
    public function pay($amount) {
        echo 'StripePayment.<br/>';
    }
}

class PayPalPayment implements PaymentStrategy {
    public function pay($amount) {
        echo 'PayPalPayment.<br/>';
    }
}

class Checkout {
    private $amount;

    public function __construct($amount) {
        $this->amount = $amount;
    }

    public function capturePayment() {
        if ($this->amount > 99.99) {
            $payment = new PayPalPayment();
        } else {
            $payment = new StripePayment();
        }

        $payment->pay($this->amount);
    }
}

$checkout = new Checkout(49.99);
$checkout->capturePayment();

$checkout = new Checkout(149.99);
$checkout->capturePayment();

?>

php策略模式(strategy pattern)-LMLPHP

05-28 09:11