What is the difference between a fluent interface and the Builder pattern?

前端 未结 2 704
温柔的废话
温柔的废话 2020-12-02 05:03

I\'m very new to design patterns and am having trouble with the difference between fluent interfaces and the Builder pattern.

I understand the concept of fluent inte

2条回答
  •  情书的邮戳
    2020-12-02 05:44

    The idea behind a Fluent interface is that one can apply multiple properties to an object by connecting them with dots, without having to respecify the object each time. The idea behind the builder pattern is that unshared mutable objects are often easier to work with than unshared immutable ones, but it's much easier to reason about shared immutable objects than shared mutable ones. Thus, code can use an an easy-to-work-with mutable object to produce a "model" of a desired instance, and then use that to make an easy-to-share immutable object that holds the same data.

    The two ideas can work well together, but are somewhat orthogonal.

    Note that there are at least three ways a fluent interface can work:

    • By having each member of an instance return a new instance with the appropriate change applied.
    • By having each member mutate the instance upon which it is invoked and return that.
    • By having each member return an instance of a lightweight patch object which holds a link to either the thing being modified or the previous patch.

    The last style requires that some action be taken to apply all the patches, but if the object being modified is large and many changes are necessary, it can minimize the amount of copying that's required.

提交回复
热议问题