Design Patterns Java - Builder Php


1) What we have done ?

First of all we created all interfaces, as it's very good practice return to client interfaces types not concrete implementation


package product;

public interface Builder
{
    Builder create(String name);

    Builder add(String name);

    Product build();
}

package product;

public interface Product
{
}

package product;

public interface ProductElement
{
}




2) What's next ?

Let's implement interfaces.


package product.impl;

public class Builder implements product.Builder
{
    private Product product;

    public Builder create(String name)
    {
        product = new Product();
        product.name = name;

        return this;
    }

    public Builder add(String name)
    {
        ProductElement element = new ProductElement();
        element.name = name;
        product.elements.add(element);

        return this;
    }

    public Product build()
    {
        Product product = this.product;
        this.product = null;
        return product;
    }
}

package product.impl;

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

class Product implements product.Product
{
    String name;
    List<ProductElement> elements = new ArrayList<>();
}

package product.impl;

class ProductElement implements product.ProductElement
{
    String name;
}




3) How client looks ?


import product.impl.Builder;
import product.Product;

public class Client
{
    public static void main(String[] args)
    {
        Product product = new Builder().create("some name")
                                       .add("element 1")
                                       .add("element 2")
                                       .add("element 3")
                                       .add("element 4")
                                       .build();
    }
}




It's nice isn't it ?

4) What have we achieved ?

- clients received nice interface for creating product
- it's very easy to differentiate: required parameters("names") and optional("elements")
- we have "Product" immutable
- "Product" is simpler, it contains only business logic not logic responsible for creating self