Fluent Interfaces Implementation

僤鯓⒐⒋嵵緔 提交于 2019-12-05 22:55:16
Incognito

Implementing fluent API using interface is good if you want to control the sequence of the calls. Let's assume that in your example when name is set you also want to allow to set age. And lets assume on top of that you need to save this changes as well, but only after when the age is set. To achieve that you need to use interfaces and use them as return types. See the example :

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
    }
}

But still follow this approach if it is good/needed for your specific case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!