极简设计模式-函数组合和集合管道模式

函数组合和集合管道模式 - Collection Pipeline

定义

    集合管道是将一些计算转化为一系列操作,每个操作的输出结果都是一个集合,同时该结果作为下一个操作的输入。在函数编程中,通常会通过一系列更小的模块化函数或运算来对复杂运算进行排序,这种方式被称为函数组合。

结构中包含的角色

Collection 集合对象

最小可表达代码 - Laravel的Collection类

class Collection 
{
    protected $items = [];

    public function __construct($items = [])
    {
        $this->items = $this->getArrayableItems($items);
    }

    public function all()
    {
        return $this->items;
    }

    public function merge($items)
    {
        return new static(array_merge($this->items, $this->getArrayableItems($items)));
    }

    public function intersect($items)
    {
        return new static(array_intersect($this->items, $this->getArrayableItems($items)));
    }

    public function diff($items)
    {
        return new static(array_diff($this->items, $this->getArrayableItems($items)));
    }

    protected function getArrayableItems($items)
    {
        if (is_array($items)) {
            return $items;
        } elseif ($items instanceof self) {
            return $items->all();
        }

        return (array) $items;
    }
}

$data = (new Collection([1,2,3]))
    ->merge([4,5])
    ->diff([5,6,7])
    ->intersect([3,4,5,6])
    ->all();

var_dump($data);

何时使用

  1. 当要执行一系列操作时。
  2. 在代码中使用大量语句时。
  3. 在代码中使用大量循环时。

实际应用场景

  1. Laravel的集合
本作品采用《CC 协议》,转载必须注明作者和本文链接
Long2Ge
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 1

实际运用场景可以丰富一些

9个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!