Fluent 接口 - 方法链 [英] Fluent Interfaces - Method Chaining

查看:40
本文介绍了Fluent 接口 - 方法链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方法链是我所知道的构建流畅界面的唯一方法.

Method chaining is the only way I know to build fluent interfaces.

以下是 C# 中的示例:

Here's an example in 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));
    }

那么其他人是如何创建流畅的界面的.你如何创造它?需要什么语言/平台/技术?

So how do others create fluent interfaces. How do you create it? What language/platform/technology is needed?

推荐答案

您可以在任何版本的 .NET 或任何其他面向对象的语言中创建流畅的界面.您需要做的就是创建一个对象,该对象的方法始终返回对象本身.

You can create a fluent interface in any version of .NET or any other language that is Object Oriented. All you need to do is create an object whose methods always return the object itself.

例如在 C# 中:

public class JohnBuilder
{
    public JohnBuilder AddSmartCode(string s)
    {
        // do something
        return this;
    }

    public JohnBuilder WithfluentInterface(string s)
    {
        // do something
        return this;
    }

    public JohnBuilder ButHow(string s)
    {
        // do something
        return this;
    }
}

用法:

John = new JohnBuilder()
    .AddSmartCode("c#")
    .WithfluentInterface("Please")
    .ButHow("Dunno");

这篇关于Fluent 接口 - 方法链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆