Builder and Fluent API

Builder: 

Like the menu in fast food restaurant, the order has a framework, and customer just fill her need.


Representive Class

The builder abstraction (interface)

The builder Implementation

A director


//The director
public class CarBuildDirector
{
    public Car Construct()
    {
        CarBuilder builder = new CarBuilder();

        builder.SetColour("Red");
        builder.SetWheels(4);

        return builder.GetResult();
    }
}

Here a car is build.  Car.Construct() calls a car builder, and returns a car.


Fluent API

A fluent interface is normally implemented by using method cascading (concretely method chaining) to relay the instruction context of a subsequent call (but a fluent interface entails more than just method chaining [1]). Generally, the context is
  • defined through the return value of a called method
  • self-referential, where the new context is equivalent to the last context
  • terminated through the return of a void context.

比如下面FirstName, LastName都是返回一个Customer的对象。这样就可以实现cascading。同时还须要有一个context的对象,来存储数据。

public Customer FirstName(string firstName)
        {
            context.fname = firstName;
            return this;
        }

        public Customer LastName(string lastName)
        {
            context.lname = lastName;
            return this;
        }

ffgdfgsd

Comments

Popular posts from this blog

Such a cold summer

My Unsolve Questions

My interview questions to a company using SAFe.