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

未匹配的标注

定义

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

一句话概括设计模式

方法链式调用 + 使用一系列更小的运算来封装一个复杂的运算。

结构中包含的角色

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的集合

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
发起讨论 查看所有版本


暂无话题~