Fluent Interfaces Implementation

旧巷老猫 提交于 2019-12-12 09:49:32

问题


In order to make my code more organized i have decided to use fluent interfaces; However by reading the available tutorials i have found many ways to implement such fluency, among them i found a topic who says that to create Fluent Interface we should make use of Interfaces, but he did not provided any good details in order to achieve it.

Here is how i implement Fluent API

Code

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

Using The Code

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

However, how could i involve Interfaces to create Fluent API in a more effective way ?


回答1:


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.



来源:https://stackoverflow.com/questions/17800706/fluent-interfaces-implementation

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