方法链接是我知道构建流畅接口的唯一方法.
这是C#中的一个例子:
John john = new JohnBuilder()
.AddSmartCode("c#")
.WithfluentInterface("Please")
.ButHow("Dunno");
Assert.IsNotNull(john);
[Test]
public void Should_Assign_Due_Date_With_7DayTermsVia_Invoice_Builder()
{
DateTime now = DateTime.Now;
IInvoice invoice = new InvoiceBuilder()
.IssuedOn(now)
.WithInvoiceNumber(40)
.WithPaymentTerms(PaymentTerms.SevenDays)
.Generate();
Assert.IsTrue(invoice.DateDue == now.AddDays(7));
}
Run Code Online (Sandbox Code Playgroud)
那么其他人如何创建流畅的界面.你是如何创造它的?需要什么语言/平台/技术?
我正在努力编写我的第一个DSL用于工作中的简单工具.我正在使用构建器模式来设置复杂的父对象,但是我遇到了砖墙,用于构建父对象的子集合.这是一个示例:
使用:
var myMorningCoffee = Coffee.Make.WithCream().WithOuncesToServe(16);
Run Code Online (Sandbox Code Playgroud)
关闭样本(我认为这就是他们所谓的):
var myMorningCoffee = Coffee.Make.WithCream().PourIn(
x => {
x.ShotOfExpresso.AtTemperature(100);
x.ShotOfExpresso.AtTemperature(100).OfPremiumType();
}
).WithOuncesToServe(16);
Run Code Online (Sandbox Code Playgroud)
示例类(没有子PourIn()方法,因为这是我想要弄清楚的.)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以在我的应用程序工作中,我有复杂的对象构建很好,但我不能为我的生活弄清楚如何获取父对象上的子集合编码的lambda.(在这个例子中,它是expresso的镜头(儿童收藏)).
也许我在这里混淆概念而且我不介意被直接设置; 但是,我真的很喜欢这个如何阅读,并想知道如何使这个工作.
谢谢,山姆
string "hello world".toLower().toUpper().replace("o", "x");
Run Code Online (Sandbox Code Playgroud)
如何使我自己的类能够在上面的示例中使用像string这样的扩展方法?也许没那么有用,但我无法弄清楚如何去做