相信有用过jquery的朋友,会清楚Jquery在使用上经常是$().fun1(…).fun2(…)这种样式的。Fluent Interface就是用来实现这种调用方式的。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testFluentInterface
{
class FluentInterfaceClass
{
public FluentInterfaceClass SaySome(string sth) { //应用Fluence Interface设计
Console.WriteLine(sth);
return this; //返回对象本身
}
public FluentInterfaceClass SaySome2(string sth) //普通的设计方式
{
Console.WriteLine(sth);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testFluentInterface
{
class Program
{
static void Main(string[] args)
{
FluentInterfaceClass fic = new FluentInterfaceClass();
fic.SaySome("1").SaySome("2").SaySome("3");//连贯的调用
Console.WriteLine("===============================================================");
fic.SaySome2("1"); //调用1次
fic.SaySome2("2"); //调用2次
fic.SaySome2("3"); //调用3次
}
}
}
从测试类中,我们可以发现FluentInterfaceClass中方法调用方式也非常简单,一直点下去就行。而普通的设计中,我们则需要通过写多次实体来调用实体的方法。