LoginSignup
0
0

デザインパターン 〜ストラテジパターン〜

Posted at

ストラテジーパターン

アルゴリズムをカプセル化し、クライアントに影響を与えずにアルゴリズムを切り替える。

例)
レストランの支払い。クレジットカード、現金、PayPalなどの複数の支払い方法を提供し、
顧客が選んだ方法に応じて支払いを処理する。
メリットは以下。

  • 柔軟性:顧客が選んだ支払い方法に応じて、支払い処理を切り替えることができる
  • 拡張性:新しい支払い方法を追加する際に。既存のコードに影響を与えずに追加できる
// 決済実行インターフェース
interface PaymentStrategy {
    public function pay(int $amount);
}

// 決済方法クラス
class CreditCardPayment implements PaymentStrategy {
    public function pay(int $amount) {
        echo "{$amount}円をクレジット決済します。";
    }
}

class PayPayPayment implements PaymentStrategy {
    public function pay(int $amount) {
        echo "{$amount}円をPayPal決済します。";
    }
}

class CashPayment implements PaymentStrategy {
    public function pay(int $amount) {
        echo "{$amount}円を現金決済します。";
    }
}

// 決済実行クラス
// PHP8からはコンストラクタで直接プロパティを初期化できるようになったみたいです。見やすくて素敵…
class Accounting {
    private $paymentStrategy;

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

    public function checkout(int $amount) {
        $this->paymentStrategy->pay($amount);
    }
}

// 顧客が選択した支払い方法で処理
$payment1 = new Accounting(new CreditCardPayment);
$payment1->checkout(1000);

$payment2 = new Accounting(new PayPayPayment);
$payment2->checkout(2000);

$payment2 = new Accounting(new CashPayment);
$payment2->checkout(3000);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0