Fluent接口实现

本文关键字:实现 接口 Fluent | 更新日期: 2023-09-27 18:24:38

为了让我的代码更有条理,我决定使用流畅的接口;然而,通过阅读现有的教程,我发现了许多实现这种流畅性的方法,其中我发现了一个主题,他说要创建Fluent Interface,我们应该使用Interfaces,但他没有提供任何好的细节来实现它

以下是我如何实现Fluent API

代码

public class Person
{
    public string Name { get; private set; }
    public int Age { get; private set; }
    public static Person CreateNew()
    {
        return new Person();
    }
    public Person WithName(string name)
    {
        Name = name;
        return this;
    }
    public Person WithAge(int age)
    {
        Age = age;
        return this;
    }
}

使用代码

Person person = Person.CreateNew().WithName("John").WithAge(21);

然而,如何让接口以更有效的方式创建Fluent API?

Fluent接口实现

如果您想控制调用的顺序,那么使用interface实现流利的API是很好的。让我们假设在您的示例中,当设置名称时,您还希望允许设置年龄。最重要的是,我们假设您也需要保存这些更改,但只有在设置了年龄之后。为了实现这一点,您需要使用接口并将它们用作返回类型。参见示例:

public interface IName
{
    IAge WithName(string name);
}
public interface IAge
{
    IPersist WithAge(int age);
}
public interface IPersist
{
    void Save();
}
public class Person : IName, IAge, IPersist
{
    public string Name { get; private set; }
    public int Age { get; private set; }
    private Person(){}
    public static IName Create()
    {
         return new Person();
    }
    public IAge WithName(string name)
    {
        Name = name;
        return this;
    }
    public IPersist WithAge(int age)
    {
        Age = age;
        return this;
    }
    public void Save()
    {
        // save changes here
    }
}

但是,如果这种方法对你的具体情况是好的/需要的,仍然要遵循这种方法。