我最初接触这个概念是读自<<模式-工程化实现及扩展>>,另外有Martin fowler大师 所写http://martinfowler.com/bliki/FluentInterface.html
Fluent Interface实例
Java 类Country
package com.jue.fluentinterface;
public class Country {
private String name;
private int code;
private boolean isDevelopedCountry;
private int area;
Country addName(String name) {
this.name = name;
return this;
}
Country addCountyCode(int code) {
this.code = code;
return this;
}
Country setDeveloped(boolean isdeveloped) {
this.isDevelopedCountry = isdeveloped;
return this;
}
Country setAread(int area) {
this.area = area;
return this;
}
}
调用类
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Country china = new Country();
china.addName("The People's Republic of China")
.addCountyCode(1001)
.setDeveloped(false)
.setAread(960);
}
主要特征:
Country 的方法返回本身country,使调用者有了继续调用country方法的能力.
优势
1.有时候我们需要根据传入的参数数目不同定义不同的构造器。使用 FluentInterface就可以随意传递想要的数据,并保持他们的连贯。
java中的应用
StringBuffer append方法