"Design mode" builder mode

Source: Internet
Author: User

Builder pattern uses multiple simple objects to build a complex object step-by-step. This type of design pattern belongs to the Create pattern, which provides an optimal way to create an object.

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

Introduced

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

Main Solution: The main solution in the software system, sometimes facing the creation of "a complex object", which is usually made up of the sub-objects of the various parts with a certain algorithm, because of the change in demand, the various parts of this complex object often face drastic changes, But the algorithms that combine them are relatively stable.

when to use: some basic components do not change, and their combinations often change.

How to Solve: will be changed and invariant points away.

Key code: Builders: Creating and delivering instances, directing: Managing Dependencies on built-up instances.

Application Example: 1, to KFC, Hamburger, Cola, French fries, fried chicken wings and so on is the same, and its combination is often changed, generated so-called "package." 2. StringBuilder in JAVA.

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

Disadvantage: 1, the product must have common ground, the scope is limited. 2, if the internal changes complex, there will be a lot of construction class.

usage Scenario: 1. Objects that need to be generated have complex internal structures. 2. The intrinsic properties of the objects that need to be generated depend on each other.

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

Realize

We assume a business case for a fast food restaurant, where a typical package can be a hamburger (Burger) and a cold drink (cold drink). Burgers (Burger) can be vegetarian burgers (Veg Burger) or chicken burgers (Chicken Burger), which are wrapped in cartons. Cold drink can be Coca-Cola (Coke) or Pepsi (Pepsi), which are packed in bottles.

We will create an item interface that represents food items (such as hamburgers and cold drinks) and an entity class that implements the item interface, and a Packing interface for food packaging and implementation Packing The entity class of the interface, the burger is wrapped in a carton, the cold drink is packed in a bottle.

Then we create a Meal class with the item ArrayList and one that creates different types of Meal objects by combining item Mealbuilder. Builderpatterndemo, our demo class uses Mealbuilder to create a Meal.

Step 1

Create an interface that represents food items and food packaging.

 Public Interface Item {   public  String name ();     Public Packing Packing ();     Public float Price ();    }

 Public Interface Packing {   public  String Pack ();}

Step 2

Create an entity class that implements the Packing interface.

 Public class Implements Packing {   @Override   public  String Pack () {      return "Wrapper";   } }
 Public class Implements Packing {   @Override   public  String Pack () {      return " Bottle ";   }}

Step 3

Creates an abstract class that implements the Item interface, which provides the default functionality.

 public  abstract  class  Burger  Item {@Override  public   Packing Packing () { return  new   Wrapper (); } @Override  public  abstract  float   Price ();}  
 Public Abstract class Implements Item {    @Override    public  Packing Packing () {       returnnew Bottle ();    }    @Override    publicabstractfloat price ();}
Step 4

Create an entity class that extends Burger and Colddrink.

 public  class  vegburger extends   Burger {@Override  public  float   Price () { return  25.0f; } @Override  public   String name () {return  "Veg Burger" 
 public  class  Chickenburger extends   Burger {@Override  public  float   Price () { return  50.5f; } @Override  public   String name () {return  "Chicken Burger" 
 public  class  Coke "extends   Colddrink {@Override  public
     float   Price () { return  30.0f; } @Override  public   String name () {return  "Coke" ; }}
 Public class extends Colddrink {   @Override   publicfloat Price () {      return 35.0f;   }   @Override   public  String name () {      return "Pepsi";   }}
Step 5

Create a Meal class with the Item object defined above.

Importjava.util.ArrayList;Importjava.util.List; Public classMeal {Privatelist<item> items =NewArraylist<item>();  Public voidAddItem (item item) {Items.Add (item); }    Public floatGetcost () {floatCost = 0.0f;  for(Item item:items) { cost+=Item.price (); }              returnCost ; }    Public voidShowitems () { for(Item item:items) {System.out.print ("Item:" +item.name ()); System.out.print (", Packing:" +item.packing (). Pack ()); System.out.println (", Price:" +Item.price ()); }           }    }
Step 6

Create a Mealbuilder class, and the actual builder class is responsible for creating the Meal object.

 Public classMealbuilder { PublicMeal preparevegmeal () {Meal Meal=NewMeal (); Meal.additem (NewVegburger ()); Meal.additem (NewCoke ()); returnmeal; }       PublicMeal preparenonvegmeal () {Meal Meal=NewMeal (); Meal.additem (NewChickenburger ()); Meal.additem (NewPepsi ()); returnmeal; }}
Step 7

Buiderpatterndemo uses Mealbuider to demonstrate builder pattern.

 Public classBuilderpatterndemo { Public Static voidMain (string[] args) {Mealbuilder Mealbuilder=NewMealbuilder (); 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 ()); }}
Step 8

Verify the output.

25.030.055.0Non-50.535.085.5

"Design mode" builder mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.