我见过许多流畅风格的api开发的例子,但有时我看到人们使用接口实现流畅,而有时人们不使用接口,只使用直接的类。我认为人们使用流畅风格的应用程序接口仅仅是因为use....means容易访问的链条。所以我想知道fluent api或实习生的性能是否还有其他好处。
这是一小段代码。
public class Coffee
{
private bool _cream;
public Coffee Make { get new Coffee(); }
public Coffee WithCream()
{
_cream = true;
return this;
}
public Coffee WithOuncesToServe(int ounces)
{
_ounces = ounces;
return this;
}
}
var myMorningCoffee = Coffee.Make.WithCream().WithOuncesToServe(16);发布于 2012-12-05 16:33:23
在你的例子中,我认为语法(即“易用性”)是唯一的优势。但是例如LINQ方法的工作方式不同--这些方法不返回this,它们返回一个新的实例。这显然是对性能的影响,但它使类成为不可变的,这在你对代码进行推理时有很大的帮助,它可以促进此类类的并行计算。
编辑(示例):在这种情况下,您的Coffee将如下所示(尽管它可能不是一个好的示例,因为在这里使用流畅的语法对我来说没有多大意义,更不用说使用新实例了)
public class Coffee
{
private bool _cream;
private int _ounces;
// I really don't like this kind of instantiation,
// but I kept it there and made static to make it work.
public static Coffee Make { get new Coffee(); }
public Coffee WithCream()
{
return new Coffee
{
_cream = true,
_ounces = this._ounces
}
}
public Coffee WithOuncesToServe(int ounces)
{
return new Coffee
{
_cream = this._cream,
_ounces = ounces
};
}当然,对于这样一个简单的类,最好使用带参数的构造函数,例如
public Coffee(int ounces, bool cream)作为一个相反的例子,我记得有一组方便的Dictionary扩展,可以流畅地添加项目,但不需要创建新的实例。类似于:
public static IDictionary<K, V> AddConditionally(
this IDictionary<K, V> source,
K key, V value)
{
// Real-life implementation would contain more checks etc.
if(!source.ContainsKey(key))
source.Add(key, value);
return source;
}您可以使用它在字典中填充一些初始数据,例如
var dict = new Dictionary<int, int>()
.AddConditionally(0,1)
.AddConditionally(1,1)
.AddConditionally(2,1)
.AddConditionally(3,1);https://stackoverflow.com/questions/13719018
复制相似问题