fluent 接口(鏈式調用的接口)
介紹
在一些框架中,比如hiberante中,比如配置系統變量時,通常都是鏈式調用來賦值的.
如下賦值就是鏈式調用:
Person person = new Person();
person.setId(1)
.setBirthday(LocalDate.of(1991, 10, 7))
.setName("Mark");
藉助this關鍵字來實現.
Java Code 示例
/**
* 嘗試寫fluent鏈式接口/類
*
* @author xuyi
* @Time 2016年12月4日 下午2:00:06
* @類名 Person
* @功能描述:
* @春風十里不如你
* @備註:
*/
public class Person
{
private int id;
private String name;
private LocalDate birthday;
public Person setId(int id)
{
this.id = id;
return this;//返回當前對象
}
public Person setName(String name)
{
this.name = name;
return this;//返回當前對象
}
public Person setBirthday(LocalDate birthday)
{
this.birthday = birthday;
return this;//返回當前對象
}
}
總結
藉助this關鍵字可以實現鏈式調用,這種接口給使用者非常好的體驗,很多優秀的框架中都有提供這樣的接口.