[PHP] 装饰器模式-结构型设计模式

前端之家收集整理的这篇文章主要介绍了[PHP] 装饰器模式-结构型设计模式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

动态地为类的实例添加功能,一层一层的套功能

先定义好接口

interface Booking{
    public function getDescription(): string;
}

 


这个就是装饰器实现了Booking,通过构造函数传递Booking对象进来

abstract class BookingDecorator implements Booking{
    protected Booking $booking;
    public function __construct(Booking $booking)
    {
        $this->booking = $booking;
    }
}

 

这个类直接实现Booking

 DoubleRoomBooking implements Booking
{
    {
        return 'double room';
    }
}

 


这个类继承了装饰器,实现了Booking

 WiFi extends BookingDecorator{
    
    {
        return $this->booking->getDescription() .  with wifi;
    }
}
 ExtraBed extends BookingDecorator
{
    public function calculatePrice(): intthis->booking->calculatePrice() + self::PRICE;
    }
     {
         with extra bed;
    }
}

 


$booking = new DoubleRoomBooking();
//继承装饰器的可以一层层套
$booking = new WiFi($booking);
$booking = new ExtraBed($booking);

猜你在找的PHP相关文章