[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

class DoubleRoomBooking implements Booking
{
    public function getDescription(): string{
        return 'double room';
    }
}

 


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

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

 


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

posted @ 2020-10-18 19:04  陶士涵  阅读(13)  评论(0编辑  收藏