Design Patterns Java - Builder Php


1) What have at the beginning ?

We have some class "Product" which has "name" and some "elements". Nothing more. Let's see code


import java.util.ArrayList;
import java.util.List;

public class Product
{
    private String name;
    private List<ProductElement> elements = new ArrayList<>();

    public Product(String name)
    {
        this.name = name;
    }

    public void addElement(ProductElement productElement)
    {
        elements.add(productElement);
    }
}

public class ProductElement
{
    private String name;

    public ProductElement(String name)
    {
        this.name = name;
    }
}





2) How objects are created ?

In Client we just call create "Product" by constructor and then we add elements for it.

public class Main
{
    public static void main(String[] args)
    {
        Product product = new Product("some name");
        product.addElement(new ProductElement("element1"));
        product.addElement(new ProductElement("element2"));
        product.addElement(new ProductElement("element3"));
        product.addElement(new ProductElement("element4"));
    }
}




3) What are the disadvantages ?

First of all we create explicitly all objects. We have to know which classes give us implementation.

Another aspect is about mutability. Let's add another requirement, we would like to have "Product" objects immutable.

There is one more problem, class "Product" will mix method responsible for logic of "Product"(in our examples we omit these methods, but of course in real code
they will exists) and method for creating itself. We want to separate this.

And final problem we would like to create some nicer interface for client.

4) How we can improve this?

Let's create Builder.