php 设计模式 策略模式

    技术2023-08-13  129

    在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。

    以出行方式为例,可以选汽车和公交

    <?php interface Trip{ public function out(); } class Car implements Trip{ public function out(){ echo '坐汽车出门'; } } class Bus implements Trip{ public function out(){ echo '坐公交出门'; } } class CheckOut{ public $out; public function __construct(Trip $trip) { $this->out = $trip; } function out(){ $this->out->out(); } } (new CheckOut(new Car()))->out();//坐汽车出门 (new CheckOut(new Bus()))->out();//坐公交出门
    Processed: 0.009, SQL: 9