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

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

问题描述



这是C#中的一个例子:

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

Assert.IsNotNull(john);

[测试]
public void Should_Assign_Due_Date_With_7DayTermsVia_Invoice_Builder()
{
DateTime now = DateTime.Now;

IInvoice发票=新的InvoiceBuilder()
.IssuedOn(现在)
.WithInvoiceNumber(40)
.WithPaymentTerms(PaymentTerms.SevenDays)
。生成();

Assert.IsTrue(invoice.DateDue == now.AddDays(7));
}

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

解决方案

您可以在任何版本的.NET或任何其他语言中创建流畅的界面即面向对象。所有你需要做的是创建一个方法总是返回对象本身的对象。



例如在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 不知道);


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

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?

解决方案

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.

For example in 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;
    }
}

Usage:

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

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

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