Builder pattern: what is and where to use

Download project ZIP

As learning by examples is the best practice to understand something, we are starting from making a certain task.

Let’s say we have an abstract shop management system. Selling items is made by dint of orders. Order entity is the main thing we work with. It needs a fundament for further conversion to plain text (for cheque output) and XML. Note that we may need to send the data in, for example, JSON format – in this case refactoring must not be a headache.

Entity model

Of course the most primary unit of shop management system is the Product entity:

This entity contains only product-related data. Point out that it is very important to separate logic in a right way to keep code clean and maintainable. As all products are sold with orders, an entity, which carries information about sale cost and quantity is needed. Call it OrderItem:

To sum up, the Order entity contains a list of OrderItems and order-related information:

Shop Management System Entities Layering

Shop Management System Entities Layering

Converters

In this case, to provide conversion extensibility, each entity must have appropriate Converter Interface:

As you see, each interface presents step-by-step conversion sequence. Such approach is very handy when it comes to complex construction.

Convert director

Each entity needs a class which handles its conversion process. It contains Convert method, which accepts an entity and converts it using Converter interface, by which director class is initialized.

Conveters

Product:

Order Item:

Order:

Putting it together

To sum up, to perform entity coversion we need:

  • Entity object
  • Converter object, which implements converter interface
  • Conversion director object, which accepts converter and handles conversion process

Builder pattern UML

Builder pattern UML


The code below is about how it works:

Such approach of building objects’ data representation is called Builder pattern.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">