Builder pattern-code understanding

table of Contents

introduction:

1. Builder mode

2. Code


introduction:

What scenario is the builder mode suitable for? : Some basic components will not change, but their combination often changes.

Reference: https://www.runoob.com/design-pattern/builder-pattern.html


1. Builder mode

Intent: To separate a complex construction from its representation, so that the same construction process can create different representations.

Main solution: The main solution is that in software systems, sometimes faced with the creation of " a complex object ", which is usually composed of sub-objects of various parts with a certain algorithm; due to changes in requirements, various parts of this complex object often face There are drastic changes, but the algorithm that combines them is relatively stable.

When to use: Some basic components will not change, but the combination often changes.

How to solve it: Separate the change from the unchanging.

Key code: Builder: Create and provide examples, Director: Manage dependencies of constructed examples.

Application examples:  1. Going to KFC, burgers, cola, french fries, fried chicken wings, etc. are unchanged, and their combination changes frequently, resulting in a so-called "set meal". 2. StringBuilder in JAVA.

Advantages:  1. The builder is independent and easy to expand. 2. It is easy to control detailed risks.

Disadvantages:  1. The products must have common points and the scope is limited. 2. If the internal changes are complicated, there will be many construction types.

Usage scenarios:  1. The object to be generated has a complicated internal structure. 2. The internal properties of the objects that need to be generated depend on each other.

Note: The difference with the factory mode is that the builder mode pays more attention to the order of parts assembly.


2. Code

As shown in the figure, it shows the interface diagram of a fast food restaurant that provides a "package" that provides a variety of food combinations. The purpose is to be able to return the corresponding "meal" according to customer requests.

Scenario: The basic components of food may not change much, but the packages provided may have different combinations.

  • First design an interface that represents food items, and then different types of food implement this interface;
  • Food has packaging, so design an interface that represents the packaging, and the specific packaging implements this interface to form an implementation class;

UML diagram of the builder pattern

Specific code reference article.

Core class:

1) Meal class with Item object:

Meal.java


import java.util.ArrayList;
import java.util.List;
 
public class Meal {
   private List<Item> items = new ArrayList<Item>();    
 
   public void addItem(Item item){
      items.add(item);
   }
 
   public float getCost(){
      float cost = 0.0f;
      for (Item item : items) {
         cost += item.price();
      }        
      return cost;
   }
 
   public void showItems(){
      for (Item item : items) {
         System.out.print("Item : "+item.name());
         System.out.print(", Packing : "+item.packing().pack());
         System.out.println(", Price : "+item.price());
      }        
   }    
}

2) MealBuilder class, the actual builder class is responsible for creating Meal objects, that is, returning different combinations.

MealBuilder.java


public class MealBuilder {
 
   public Meal prepareVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new VegBurger());
      meal.addItem(new Coke());
      return meal;
   }   
 
   public Meal prepareNonVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new ChickenBurger());
      meal.addItem(new Pepsi());
      return meal;
   }
}

3) Use MealBuilder to generate Meal objects and test:

public class BuilderPatternDemo {
   public static void main(String[] args) {
      MealBuilder mealBuilder = new MealBuilder();
 
      Meal vegMeal = mealBuilder.prepareVegMeal();
      System.out.println("Veg Meal");
      vegMeal.showItems();
      System.out.println("Total Cost: " +vegMeal.getCost());
 
      Meal nonVegMeal = mealBuilder.prepareNonVegMeal();
      System.out.println("\n\nNon-Veg Meal");
      nonVegMeal.showItems();
      System.out.println("Total Cost: " +nonVegMeal.getCost());
   }
}
执行程序,输出结果:

Veg Meal
Item : Veg Burger, Packing : Wrapper, Price : 25.0
Item : Coke, Packing : Bottle, Price : 30.0
Total Cost: 55.0


Non-Veg Meal
Item : Chicken Burger, Packing : Wrapper, Price : 50.5
Item : Pepsi, Packing : Bottle, Price : 35.0
Total Cost: 85.5

3. Summary

In one sentence: Provide an object that returns different combinations of several components.

Guess you like

Origin blog.csdn.net/Longtermevolution/article/details/107865659