Java builder pattern

Posted by gilgimech on Sat, 02 Oct 2021 00:08:19 +0200

Java builder pattern

introduce

Main solutions: it mainly solves the problem of creating "a complex object" in software system, which is usually composed of sub objects of each part with certain algorithms; Due to the change of requirements, each part of this complex object often faces drastic changes, but the algorithm that combines them is relatively stable.

When to use: when some basic components will not change, but their combinations often change.

Application examples: 1. Go to KFC, hamburger, coke, French fries, fried chicken wings, etc. are unchanged, and their combination changes frequently to generate the so-called "set meal".

Advantages: 1. The builder is independent and easy to expand. 2. Easy to control detail risk.

Disadvantages: 1. The products must have something in common and the scope is limited. 2. If the internal changes are complex, there will be many construction classes.

Usage scenario: for example, the mobile phone package for buying mobile phones, the combined package for buying clothes, such as the combined package for taking out

Note: the builder mode pays more attention to part assembly.

realization

Let's assume a business case of a fast food restaurant, in which a typical set meal can be a Burger and a Cold drink.

Burger s can be veg burgers or chicken burgers, which are wrapped in cartons.

Cold drink s can be Coca Cola or pepsi, which are packed in bottles.

We will create a commodity Item interface Item and an entity class that implements the Item interface, as well as a Packing interface that represents food packaging and an entity class that implements the Packing interface,

Hamburgers are wrapped in cartons and cold drinks are packed in bottles.

Then we create a meal (package) class, including ArrayList with Item and the package production class MealBuilder.

Use builderpatterndemo (test class) to demonstrate the class, and use MealBuilder to create a meal (package).

It doesn't matter if you can't understand the above picture now. When you understand the following cases, you can understand it when you come back and look at this picture

Item interface

public interface Item {
    String name();  //Trade name
    Packing packing(); //Commodity packaging
    float price();//commodity price
}

Because the wrapper is fixed, we can extract it and implement it in an abstract class

The price and commodity are not fixed. We can realize it through different subclasses

This is helpful to code expansion, code reuse and reduce code redundancy

Burger abstract class

//hamburger
public abstract class Burger implements Item {
    //Realize hamburger packaging
    @Override
    public Packing packing() {
        return new Wrapper();
    }
}

Implementation class of chicken hamburger

//Chicken Burger
public class ChickenBurger extends Burger {
    //Hamburg price
    @Override
    public float price() {
        return 50.5f;
    }
    //name
    @Override
    public String name() {
        return "Chicken Burger";
    }
}

VegBurger implementation class of vegetable Burger

//Veggie burger 
public class VegBurger extends Burger {

    //Price
    @Override
    public float price() {
        return 25.0f;
    }
    //name
    @Override
    public String name() {
        return "Veggie burger ";
    }
}

Cold drink abstract class ColdDrink

//cold drink
public abstract class ColdDrink implements Item {
    //Realize cold drink packaging
    @Override
    public Packing packing() {
        return new Bottle();
    }

}

Coca Cola

//Mouth delicious music
public class Coke extends ColdDrink {
    //Price
    @Override
    public float price() {
        return 30.0f;
    }
    //name
    @Override
    public String name() {
        return "Coca Cola";
    }
}

Pepsi Pepsi

//Pepsi Cola
public class Pepsi extends ColdDrink {
    //Price
    @Override
    public float price() {
        return 35.0f;
    }
    //name
    @Override
    public String name() {
        return "Pepsi Cola";
    }
}

Packaging interface

public interface Packing {
     String pack();//packing
}

Bottled Bottle

public class Bottle implements Packing {
    @Override
    public String pack() {
        return "bottled";
    }
}

Wrapper

public class Wrapper implements Packing {

    @Override
    public String pack() {
        return "Box wrapping paper";
    }
}

Package Meal

//Package
public class Meal {
    //The collection of packages stores all the products of the package
    private List<Item> items = new ArrayList<Item>();
    //Add item
    public void addItem(Item item){
        items.add(item);
    }
    //Calculate the total price of goods in the package
    public float getCost(){
        float cost = 0.0f;
        for (Item item : items) {
            cost += item.price();
        }
        return cost;
    }
    //Print all items in the current package
    public void showItems(){
        for (Item item : items) {
            System.out.println("{ Trade name:"+item.name()+", packing:"+item.packing().pack()+", Price : "+item.price()+"}");
        }
    }
}

With the package class, we can produce packages in the list < item >

Production package MealBuilder

//Production package
public class MealBuilder {

    //  Vegetarian package
    public Meal prepareVegMeal (){
        Meal meal = new Meal();
        //Veggie burger 
        meal.addItem(new VegBurger());
        //Coca Cola
        meal.addItem(new Coke());
        return meal;
    }
//        Non vegetarian package
    public Meal prepareNonVegMeal (){
        Meal meal = new Meal();
        //Chicken Burger
        meal.addItem(new ChickenBurger());
        //Pepsi Cola
        meal.addItem(new Pepsi());
        return meal;
    }
}

Test BuilderPatternDemo

public class BuilderPatternDemo {
    public static void main(String[] args) {
        MealBuilder mealBuilder = new MealBuilder();

        Meal vegMeal = mealBuilder.prepareVegMeal();
        System.out.println("---------------Vegetarian package----------------");
        vegMeal.showItems();
        System.out.println("Total price: " +vegMeal.getCost());

        Meal nonVegMeal = mealBuilder.prepareNonVegMeal();
        System.out.println("\n\n----------------------Non vegetarian package----------------------");
        nonVegMeal.showItems();
        System.out.println("Total price: " +nonVegMeal.getCost());
    }
}

---------------Vegetarian----------------
Commodity: {vegetable hamburger packaging: wrapping paper, price: 25.0}
Commodity: {Coca Cola packaging: bottled, price: 30.0}
Total price: 55.0

----------------------Non vegetarian----------------------
Commodity: {chicken hamburger packaging: wrapping paper, price: 50.5}
Commodity: {Pepsi Cola packaging: bottled, price: 35.0}
Total price: 85.5

Like - collect - pay attention - easy to review and receive the latest content in the future If you have other questions to discuss in the comment area - or send me a private letter - you will reply as soon as you receive them In case of infringement, please contact me by private letter Thank you for your cooperation. I hope my efforts will be helpful to you^_^

Topics: Java Design Pattern Algorithm