When to use builder pattern?
- The builder pattern is used when we need to create complex objects which require many configuration values.
- It’s a good choice when the objects to be created can usually use some predefined defaults, and are rarely modified.
- Callers can customize these default configuration values, but most of the time the defaults remain unchanged.
- This pattern encapsulates the default configuration values and the required set-up logic required to create an object into a builder class.
- The builder pattern separates the configuration of an object from its creation.
- It simplifies the creation of instances which need many default values, and those values usually don’t change frequently when creating new objects.
The builder pattern separates the creation of object from its configuration thereby simplifying the creation of complex objects.
- Theme builder for a web app or mobile apps – the background color, navigation bar color, text color size, etc. A dark theme or a light theme will have its own set of values which you can customize if needed. Theme builders are used in code editors and mobile apps
- Network session managers – here a session is started with a default set of values.
- A meal builder in McDonald’s – the user just has to mention the name of the meal and all parts of the meal are built and without user involving in the complexity of creation. Yet user can customise if needed.
Summary : A Builder design pattern is the best fit when an instance implies complex configuration steps and you don’t need to change the settings frequently while creating new objects. Also when you need to separate the configuration of objects from their creation. Callers only provide minimal configuration values. The builder class contains all the logic to set the default configuration values required while building the object.