流式接口 fluent interface

流式接口(Fluent Interface)是一种面向对象API的设计方式,旨在提升代码可读性。该接口常通过方法链式调用来实现对象方法调用的上下文传递,如PHP中的自引用返回实例。C++的iostream和Smalltalk早有类似实践。在PHP中,可以通过`$this`返回当前对象,实现方法的链式调用,例如在设置Employee类的属性时。此外,流式接口也被应用于数据库查询,如jQuery库的动态查询。
摘要由CSDN通过智能技术生成

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<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值