Builder pattern

The Builder pattern is used in situations where the creation of a complex object is required, and the creation is generally achieved through a number of steps until the final product is ready.

A classic example is that of a car as a final product, which is created in steps by adding the engine, chassis, body, tires, and so on. The main client asks for the product and receives the final product with all the creation steps hidden from it. This is achieved via a Director class.

The basic builder pattern involves a Director, Builder, and Product class, as shown in the following diagram:

Let's look at an example in the code. We will build up our previous example of a sample GUI app that added the menu, status bar, and wizard screen.

Remember, we had the abstract factory pattern applied in order to build our UI controls, and one of the methods of this factory class was CreateWizard(). For the example, we suppose that creating the wizard means adding a couple of screens to create one flow of a wizard operation common in some types of user applications. Therefore, creating a wizard is achieved through a number of steps internally by the CreateWizard() method, and these steps are essentially the builder pattern, that is, to simplify the creation of a complex product.

Let's take a look at the interface of our builder class:

    public interface IWizardBuilder 
{
void CreateWizardSteps(int screenSteps);
void AddFrontScreen();
void AddFinalScreen();

IWizard GetResult();
}

The code that uses the builder object to create the product in correct steps is basically done by Director according to the builder pattern, which in our example is the code inside the CreateWizard() method of the abstract factory:

    /// <summary> 
/// Internal code demonstrates the use of Builder pattern
/// </summary>
/// <returns></returns>
public IWizard CreateWizard()
{
//Director code for builder pattern
var wizardBuilder =
_provider.GetRequiredService<IWizardBuilder>();

wizardBuilder.CreateWizardSteps(4);
wizardBuilder.AddFrontScreen();
wizardBuilder.AddFinalScreen();

var wizard = wizardBuilder.GetResult();

ApplyThemeOnWizard(wizard);

return wizard;
}

Note that the following line is retrieving the correct build object using the DI container:

    var wizardBuilder =
_provider.GetRequiredService<IWizardBuilder>();

You do not need to go into its detail; this DI container is explained in the Dependency injection support with .NET Core section within this chapter.

From the preceding code, you can see how the wizard in our example application is actually created in steps using the builder pattern.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.99.71