理解Fluent Interface

Fluent Interface 直译过来是 “流畅(流利)的接口”,照字面有点难以理解。
咱们还是从用代码来说明 (c#)
public interface IRect
{
       void SetWidth(int width);
       void SetHeight(int height);
}
public Rect : IRect
{
       private int _width;
       private int _height;
       public void SetWidth(int width) { this._width = width; }
       public void SetHeight(int height){ this_height = height; }
}
public static void Main(string [] args)
{
       IRect rect = new Rect();
       rect.SetHeight(10);
       rect.SetWidth(50);
}
没有什么花俏的东西,一个可设长宽的矩形接口并提供一个简单实现。接下来看看用另一种方式
public interface IRectFluent
{
       IRectFluent SetWidth(int width);
       IRectFluent SetHeight(int height);
}
public RectFluent : IRectFluent
{
       private int _width;
       private int _height;
       public IRectFluent SetWidth(int width) { this._width = width; return this; }
       public IRectFluent SetHeight(int height){ this_height = height; return this; }
}
public static void Main(string [] args)
{
       IRectFluent rect = new RectFluent();
       rect.SetHeight(10).SetWidth(50);  // checkpoint
}
这种“链式"方法调用方式是不是更接近我们人脑的思维方式,更简洁呢。没错, It's Fluent Interface。
个人理解的Fluent Interface 就是 在面向对象编程中,使用某种方式(通常但不限于使用 方法链方式)来实现更具可读性,易用性的编程方式。而方法链的关键之处就是在方法内部调用最后要返回调用者本身。
所谓Fluent借助于wikipedia的说法就是‘This style is beneficial due to its ability to provide a more fluid feel to the code."
说到这里,经常使用jquery的朋友肯定感觉很熟悉上面的使用方式。
没错,类似于 $('id').show().css('').fadeOut(); 这种就是一种Fluent Interface实现。
类似的应用此种实现手法的还有Fluent NHibernate
WIKI: Fluent_Interface

posted on 2009-06-29 13:19  yyliuliang  阅读(899)  评论(0编辑  收藏  举报

导航