1. Schema definition

The Builder Pattern uses multiple simple objects to build a complex object step by step. This type of design pattern is the creation pattern, which provides the best way to create objects.

A Builder class constructs the final object step by step. The Builder class is independent of other objects.

introduce

Intent: Separate a complex build from its representation so that the same build process can create different representations.

Main solution: main solution in the software system, sometimes faced with “a complex object” to create work, which is usually composed of each part of the sub-object with a certain algorithm; The pieces of this complex object often face drastic changes due to changing requirements, but the algorithms that put them together are relatively stable.

When to use: When some basic components do not change, but the combination often changes.

How to solve it: Separate change from immobility.

Key code: Builder: creates and provides instances, director: manages the dependencies of built instances.

1, go to KFC, hamburger, Coke, French fries, fried chicken wings and so on are unchanged, but their combination is often changed, generating the so-called “set meal”. StringBuilder in JAVA.

Advantages: 1, independent builder, easy to expand. 2, easy to control the details of risk.

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

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

Note: The difference from factory mode is that builder mode is more concerned with the order in which parts are assembled.

Spring source code application

org.springframework.web.serlet.mvc.method.RequestMappingInfo
org.springframework.beans.factory.support.BeanDefinitionBuilder
Copy the code

2. Code implementation

(1) Original demand

Let’s consider the business case of a fast food restaurant where a typical meal can be a Burger and a Cold drink. A Burger, “Burger,” can be a Veg Burger or a Chicken Burger, and they come in a carton. A Cold drink, “Cold drink,” can be a Coke or a Pepsi. It comes in a bottle.

We’ll create an Item interface that represents food items (such as burgers and cold drinks) and an entity class that implements the Item interface, as well as an entity class that represents Packing for food and implements Packing, with burgers in cartons and cold drinks in bottles.

Then we create a Meal class, an ArrayList with items, and a MealBuilder that creates different types of Meal objects by combining items. The BuilderPatternDemo class uses MealBuilder to create a Meal.

(2) Create an interface that represents food items and food packaging

public interface Item {
   public String name(a);
   public Packing packing(a);
   public float price(a);    
}
public interface Packing {
   public String pack(a);
}
Copy the code

(3) Create an entity class that implements Packing interface

public class Wrapper implements Packing {
 
   @Override
   public String pack(a) {
      return "Wrapper"; }}public class Bottle implements Packing {
 
   @Override
   public String pack(a) {
      return "Bottle"; }}Copy the code

(4) Create an abstract class that implements the Item interface and provides default functionality

public abstract class Burger implements Item {
 
   @Override
   public Packing packing(a) {
      return new Wrapper();
   }
 
   @Override
   public abstract float price(a);
}
public abstract class ColdDrink implements Item {
 
    @Override
    public Packing packing(a) {
       return new Bottle();
    }
 
    @Override
    public abstract float price(a);
}
Copy the code

(5) Create entity classes that extend Burger and ColdDrink

public class VegBurger extends Burger {
 
   @Override
   public float price(a) {
      return 25.0 f;
   }
 
   @Override
   public String name(a) {
      return "Veg Burger"; }}public class ChickenBurger extends Burger {
 
   @Override
   public float price(a) {
      return 50.5 f;
   }
 
   @Override
   public String name(a) {
      return "Chicken Burger"; }}public class Coke extends ColdDrink {
 
   @Override
   public float price(a) {
      return 30.0 f;
   }
 
   @Override
   public String name(a) {
      return "Coke"; }}public class Pepsi extends ColdDrink {
 
   @Override
   public float price(a) {
      return 35.0 f;
   }
 
   @Override
   public String name(a) {
      return "Pepsi"; }}Copy the code

(6) Create a Meal class with the Item object defined above

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

(7) Create a MealBuilder class. The actual Builder class is responsible for creating Meal objects

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

(8) BuiderPatternDemo uses MealBuilder to demonstrate Builder Pattern

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()); }}Copy the code

(9) Execute the program and output the results