流接口模式 Fluent Interface Pattern
定义
在软件工程中,流接口是指实现一种面向对象的,能提高代码可读性的API的方法。其目的就是可以编写具有自然语言一样可读性的代码。这种模式属于结构型模式。流式接口通常采取方法瀑布调用(具体说是方法链式调用)来转发一系列对象方法调用的上下文。
一句话概括设计模式
方法链式调用 + 如何命名和构造代码让API更具可读性。
结构中包含的角色
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)));
}
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])
->all();
var_dump($data);
实际应用场景
- laravel的Builder
推荐文章: