mardi 19 septembre 2017

Fluent Builder pattern which returns root type

I want to create builder for my purpose, with such call chain:

User user = new CommonBuilder(new UserNode()).Root //generic parameter, currently is User
    .Group.Group.Folder.Build();

Here is the code, which I use:

public abstract class AbstractNode
{
    public Guid Id { get; } = Guid.NewGuid();
}

public abstract class AbstractNode<T> where T : AbstractNode<T>
{

}

public class CommonBuilder<T> where T : AbstractNode<T>
{
    public T Root { get; private set; }
    public CommonBuilder(T root)
    {
        Root = root;
    }
}

public class UserNode : AbstractNode<UserNode>
{
    private GroupNode _group;
    public GroupNode Group
    {
        get
        {
            if (_group is null)
            {
                _group = new GroupNode();
            }
            return _group;
        }
    }
}

public class GroupNode : AbstractNode<GroupNode>
{
    private GroupNode _group;
    public GroupNode Group
    {
        get
        {
            if (_group is null)
            {
                _group = new GroupNode();
            }
            return _group;
        }
    }

    private FolderNode _folder;
    public FolderNode Folder
    {
        get
        {
            if (_folder is null)
            {
                _folder = new FolderNode();
            }
            return _folder;
        }
    }
}

public class FolderNode : AbstractNode<FolderNode>
{

}

The problem is in the Build() method, which need to return Root from CommonBuilder, not the File.

Where must I place Build() method, which must be always called at the end of a chain, which returns Root of a builder?

Aucun commentaire:

Enregistrer un commentaire