1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
| import java.util.ArrayList; import java.util.List;
interface Packing { String pack(); }
interface Item { String name(); Packing packing(); float price(); }
class Wrapper implements Packing {
@Override public String pack() { return "Wrapper"; } }
class Bottle implements Packing {
@Override public String pack() { return "Bottle"; } }
abstract class Burger implements Item {
@Override public Packing packing() { return new Wrapper(); }
@Override public abstract float price(); }
abstract class ColdDrink implements Item {
@Override public Packing packing() { return new Bottle(); }
@Override public abstract float price(); }
class VegBurger extends Burger {
@Override public float price() { return 25.0f; }
@Override public String name() { return "Veg Burger"; } }
class ChickenBurger extends Burger {
@Override public float price() { return 50.5f; }
@Override public String name() { return "Chicken Burger"; } }
class Coke extends ColdDrink {
@Override public float price() { return 30.0f; }
@Override public String name() { return "Coke"; } }
class Pepsi extends ColdDrink {
@Override public float price() { return 35.0f; }
@Override public String name() { return "Pepsi"; } }
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()); } } }
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; } }
public class BuilderDemo { 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()); } }
|