wiki:https://www.wikiwand.com/zh/%E6%B5%81%E5%BC%8F%E6%8E%A5%E5%8F%A3
流式接口(fluent interface)是软件工程中面向对象API的一种实现方式,以提供更为可读的源代码。最早由Eric Evans(英语:Eric Evans (technologist))与Martin Fowler于2005年提出。
通常采取方法瀑布调用(英语:enmethod cascading) (具体说是方法链式调用(英语:method chaining))来转发一系列对象方法调用的上下文 。这个上下文(context)通常是指:
通过被调方法的返回值定义
自引用,新的上下文等于老的上下文。
返回一个空的上下文来终止。
C++的iostream流式调用就是一个典型的例子。Smalltalk在1970年代就实现了方法瀑布调用(英语:enmethod cascading)。
例子
PHP
In PHP, one can return the current object by using the $this
special variable which represent the instance. Hence return $this
; will make the method return the instance. The example below defines a class Employee and three methods to set its name, surname and salary. Each return the instance of the Employee class allowing to chain methods.
<?php
class Employee
{
public $name;
public $surName;
public $salary;
public function setName($name)
{
$this->name = $name;
return $this;
}
public function setSurname($surname)
{
$this->surName = $surname;
return $this;
}
public function setSalary($salary)
{
$this->salary = $salary;
return $this;
}
public function __toString()
{
$employeeInfo = 'Name: ' . $this->name . PHP_EOL;
$employeeInfo .= 'Surname: ' . $this->surName . PHP_EOL;
$employeeInfo .= 'Salary: ' . $this->salary . PHP_EOL;
return $employeeInfo;
}
}
# Create a new instance of the Employee class, Tom Smith, with a salary of 100:
$employee = (new Employee())
->setName('Tom')
->setSurname('Smith')
->setSalary('100');
# Display the value of the Employee instance:
echo $employee;
# Display:
# Name: Tom
# Surname: Smith
# Salary: 100
JavaScript
用于数据库查询的jQuery,例如https://github.com/Medium/dynamite :
// getting an item from a table
client.getItem('user-table')
.setHashKey('userId', 'userA')
.setRangeKey('column', '@')
.execute()
.then(function(data) {
// data.result: the resulting object
})
JavaScript使用原形继承与this
.
// example from http://schier.co/post/method-chaining-in-javascript
// define the class
var Kitten = function() {
this.name = 'Garfield';
this.color = 'brown';
this.gender = 'male';
};
Kitten.prototype.setName = function(name) {
this.name = name;
return this;
};
Kitten.prototype.setColor = function(color) {
this.color = color;
return this;
};
Kitten.prototype.setGender = function(gender) {
this.gender = gender;
return this;
};
Kitten.prototype.save = function() {
console.log(
'saving ' + this.name + ', the ' +
this.color + ' ' + this.gender + ' kitten...'
);
// save to database here...
return this;
};
// use it
new Kitten()
.setName('Bob')
.setColor('black')
.setGender('male')
.save();