Fluent interface

In software engineering, a fluent interface (as first coined by Eric Evans and Martin Fowler) is an implementation of an object oriented API that aims to provide for more readable code.

A fluent interface is normally implemented by using method cascading (concretely method chaining) to relay the instruction context of a subsequent call (but a fluent interface entails more than just method chaining [1]). Generally, the context is

  • defined through the return value of a called method
  • self-referential, where the new context is equivalent to the last context
  • terminated through the return of a void context.

 

History[edit]

The term "fluent interface" was coined in late 2005, though this overall style of interface dates to the invention of method cascading in Smalltalk in the 1970s, and numerous examples in the 1980s. The most familiar is the iostream library in C++, which uses the << or >>operators for the message passing, sending multiple data to the same object and allowing "manipulators" for other method calls. Other early examples include the Garnet system (from 1988 in Lisp) and the Amulet system (from 1994 in C++) which used this style for object creation and property assignment.

 

Examples[edit]

Java[edit]

The jOOQ library models SQL as a fluent API in Java


1

2

3

4

5

6

Author a = AUTHOR.as("a");

create.selectFrom(a)

      .where(exists(selectOne()

                   .from(BOOK)

                   .where(BOOK.STATUS.eq(BOOK_STATUS.SOLD_OUT))

                   .and(BOOK.AUTHOR_ID.eq(a.ID))));

  

The op4j library enables the use of fluent code for performing auxiliary tasks like structure iteration, data conversion, filtering, etc.


1

2

3

4

String[] datesStr = new String[] {"12-10-1492""06-12-1978"};

...

List<Calendar> dates =

    Op.on(datesStr).toList().map(FnString.toCalendar("dd-MM-yyyy")).get();

  

The fluflu annotation processor enables the creation of a fluent API using Java annotations.

Also, the mock object testing library EasyMock makes extensive use of this style of interface to provide an expressive programming interface.


1

2

Collection mockCollection = EasyMock.createMock(Collection.class);

EasyMock.expect(mockCollection.remove(null)).andThrow(new NullPointerException()).atLeastOnce();

  

In the Java Swing API, the LayoutManager interface defines how Container objects can have controlled Component placement. One of the more powerful LayoutManager implementations is the GridBagLayout class which requires the use of the GridBagConstraints class to specify how layout control occurs. A typical example of the use of this class is something like the following.


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

GridBagLayout gl = new GridBagLayout();

JPanel p = new JPanel();

p.setLayout( gl );

  

JLabel l = new JLabel("Name:");

JTextField nm = new JTextField(10);

  

GridBagConstraints gc = new GridBagConstraints();

gc.gridx = 0;

gc.gridy = 0;

gc.fill = GridBagConstraints.NONE;

p.add( l, gc );

  

gc.gridx = 1;

gc.fill = GridBagConstraints.HORIZONTAL;

gc.weightx = 1;

p.add( nm, gc );

  

This creates a lot of code and makes it difficult to see what exactly is happening here. The Packer class, visible at http://java.net/projects/packer/, provides a Fluent mechanism for using this class so that you would instead write:


1

2

3

4

5

6

7

8

JPanel p = new JPanel();

Packer pk = new Packer( p );

  

JLabel l = new JLabel("Name:");

JTextField nm = new JTextField(10);

  

pk.pack( l ).gridx(0).gridy(0);

pk.pack( nm ).gridx(1).gridy(0).fillx();

  

There are many places where Fluent APIs can greatly simplify how software is written and help create an API language that helps users be much more productive and comfortable with the API because the return value of a method always provides a context for further actions in that context.

时间: 2024-08-02 06:30:42

Fluent interface的相关文章

单元测试中的Fluent Interface

测试的重要性是每个程序员都明白的, 但真正自己去做测试(Unit Test)的却很少, 曾经我也是其中的一员. 因为写个main调用一些方法, 打印出结果或状态, 然后人工肉眼去排查, 若不是迫于无奈, 我相信没有程序员愿意纠结于这些琐碎的东西. 其实, 测试本可以很有趣的.借助JUnit, 我们可以将测试按不同的场景组织起来, 在"一键"之后的红绿条的反馈下, 快速解决代码中存在的问题. 如果你还不太了解JUnit, 请先去这里. 后文将以JUnit为基础, 以Fluent Inte

.NET验证组件Fluent Validation使用指南_实用技巧

认识Fluent Vaidation. 看到NopCommerce项目中用到这个组建是如此的简单,将数据验证从业务实体类中分离出来,真是一个天才的想法,后来才知道这个东西是一个开源的轻量级验证组建.   Fluent Validation 翻译为:流畅验证   开源Codeplex其主页简介:该组件是一个轻量级的.NET类库,使用流畅的接口定义和lambda表达式为构建一个业务类的验证规则(A small validation library for .NET that uses a fluen

Unity(七):使用场景Ⅲ:用于依赖注入(下)

Fluent interface 上一篇文章我使用到了Fluent interface这个特性,但是这一点忘了交代了,不好意思...补上! 先来看段代码: 咋看上去,可能会有些不习惯,但是再仔细看,又会觉得表意很清楚,能够很顺畅的把这段代码阅读下来.这个特性叫做Fluent interface(我还不清楚中文统一的翻译是什么),具体可以参见Martin Fowler的http://martinfowler.com/bliki/FluentInterface.html一文,这个概念也是Martin

.Net架构必备工具列表

原文:.Net架构必备工具列表 N多年前微软官网曾发了.Net下必备的十种工具,N多年过去了,世异时移,很多东西都已经变化了,那个列表也似乎陈旧了.而且,该文也只是对十种工具独立的介绍,显得有些罗列的感觉,是不是每个工具都是同等重要,工具与工具之间是否有联系?等等,阐述得并不明确. 这里,我想从另一个角崖,重新归纳一个更新的更实际的武器库.更新,是因为有很多最近几年才出来的工具/框架库,更实际,是因为我自己的项目就完全依赖使用. Visual Studio 这个似乎是不言而喻的,只是从严谨的角度

阿里巴巴开源技术汇总:115个软件(五)

很高兴又和广大读者相见了!今天是第五期阿里巴巴开源技术汇总.在前面四期中我们带领大家浏览了许多阿里的开源项目,相信现在读者们跟我一样对阿里的很多优秀的项目都耳熟能详了.在今天这一期的汇总中,我们又为读者呈现了20个精彩的开源项目,20个新的面孔,现在就和我们一起走近它们,领略它们的风采吧! 1.TimeTunnel [项目简介] TimeTunnel(简称TT)是一个基于thrift通讯框架搭建的实时数据传输平台,具有高性能.实时性.顺序性.高可靠性.高可用性.可扩展性等特点.目前TimeTun

awesome-android

awesome-android https://github.com/snowdream/awesome-android Introduction android libs from github System requirements Android Notice If the lib is no longer being maintained,please do not add it here. How To Contribute Step 1. Add a Item as follows:

Java JWT: JSON Web Token

  Java JWT: JSON Web Token for Java and Android JJWT aims to be the easiest to use and understand library for creating and verifying JSON Web Tokens (JWTs) on the JVM. JJWT is a Java implementation based on the JWT, JWS, JWE, JWK and JWA RFC specific

应用FluenceInterface设计让使用者更方便

--<设计模式_基于C#的工程化实现及扩展> 相信有用过jquery的朋友,会清楚Jquery在使用上经常是$().fun1(-).fun2(-)这种样式的.Fluent Interface就是用来实现这种调用方式的.   一个简单的FluentInterface类设计 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace testFluentInterfa

Thumbnailator v0.3.0发布 图像缩略图的Java类库

Thumbnailator 是一个用来生成图像缩略图的 Java 类库,通过很简单的代码即可生成图片缩略图,也可直接对一整个目录的图片生成缩略图. File originalhttp://www.aliyun.com/zixun/aggregation/19352.html">File = new File("original.jpg");File thumbnailFile = new File("thumbnail.jpg");Thumbnail