Builder pattern - better understand c# example on wikipedia

The builder pattern c# code example looks overly complex to me. Am i mistaken?

I understood that goal of the builder pattern is:

  1. to Encapsulate creating a complex object
  2. classes using this object should be independent of the creation of the complex object

To fullfill goal 1 and 2 a builder class is needed. Based on the example it seem to me that the needed ingredients are only these

- car represents a complex object of "Type Car"

- Client is the class that would like to use a car object

- FerrariBuilder creates certain complex cars

​

I believe the pseudocode below matches the pseudocode in the article:

// create a complex object using a builder class
var ferrariDiablo  = new CarBuilder(setOption1, setOption2, ...).getResult();
//  in the constructor or in getRestult additional properties are set

// inject the complex object to the class using it
var client = new Client(ferrariDiablo);

var client.DriveCar();  // work with the object internally

The example in the wikipedia-article uses on top a Director-Class and IBuilder-Interface. The code below is from the wikipedia and the comments are mine

public class Client
{
   public void DoSomethingWithCars()
   {
      // FerrariBuilder is a class that returns an "empty" builderObject
      var builder = new FerrariBuilder(); 
      
      // it seems that director is just some meaningless object
      var director = new SportsCarBuildDirector(builder); 
      

      // the Construct-Method is used to set more properties on the builderObject
      // it sets Colour="Red" + NumDoors=2 
      director.Construct(); 

      // GetResult() from class FerrariBuilder 
      // returns new Car("Ferrari", "488 Spider") if Doors==2
      Car myRaceCar = builder.GetResult(); 
   }
}

To my understanding the FerrariBuilder is the class that takes care of building the complex object. The Client uses the car without any knowledge how to create a Ferrari.

​

  1. Why does the sample use a builder and a director?
  2. Contains the c# code of the wiki-article more classes, method calls, object creations than needed?
  3. Could the director-class and the Interface be removed without loosing the purpose of the builder pattern?

Thank you

Posted Dec 6, 2018, 1:09 AM UTC · edited

10
Loading comments…