“Separate the construction of a complex object from its representation so that the same construction process can create different representations”
- Used when an object can be created in a variety of ways, or involves lots of steps
- The builder only has one job: fill in the object with data from some other location
- It is familiar with the target object and the input source.
- Can be a method or a class
- Classes can leverage inheritance for common functions when working with the target object.
public class Builder {
virtual Portfolio Build();
}
Now data can be accessed from various sorces – DB, file, Web service etc. How can be builder class controoled – again you can use here Factory Pattern discussed:
public class BuilderFactory
{
BuilderFactory() {}
virtual Builder DBBuilder(IDBConnection db);
virtual Builder WebServiceBuilder(string URL);
virtual Builder ScraperBuilder(string URL);
…
}
And here is how Builder Factoy Implemented:
static void Main() {
BuilderFactory factory;
Builder builder;
switch( typeBuild ) {
case “DB”: builder = factory.DBBuilder(db);
case "WebService": builder = factory.WebServiceBuilder(url);
}
Portfolio portfolio = builder.Build();
}
From above example –
- The caller only will care about the base class.
- Some of the creation details should be hidden
Links: