描述“堆”抽象数据类型(ADT)行为的接口。

v1.0.0 2019-08-03 02:51 UTC

This package is not auto-updated.

Last update: 2024-09-23 07:27:57 UTC


README

描述“堆”抽象数据类型(ADT)行为的接口。

安装

在您的项目/库中使用这些接口的最佳方式是通过 Composer

$ composer require collection-interop/stack

用法

final class DeviceHistory implements \Interop\Collection\Stack
{
    private $commands = [];
    private $type = '';
    
    public function push(object $item): void
    {
        if (!$this->type) {
            $this->type = get_class($item);
        }
        
        if (!($item instanceof $this->type)) {
            throw new InvalidArgumentException(
                sprintf('Item must be an instance of %s. Instance of %s was given instead.', $this->type, get_class($item))
            );
        }
        
        $this->commands[] = $item;
    }
    
    public function pop(): object
    {
        return array_pop($this->commands);
    }
}

final class Command
{
    public $action;
    public function __construct(string $action) {
        $this->action = $action;
    }
}

final class TurnOffCommand
{
    public $action = 'turn-off';
}

$history = new DeviceHistory();
$history->push(new Command('turn-on'));
//$history->push(new TurnOffCommand());   // uncomment line to verify that only objects of same type can be added
$history->push(new Command('change-channel'));

var_dump($history->pop());  // returns 'change-channel'
var_dump($history->pop());  // returns 'turn-on'