Created
June 19, 2016 11:00
-
-
Save mitulmanish/c116cf9e1c936298b66abfc837c045e3 to your computer and use it in GitHub Desktop.
Builder Pattern implemented in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
interface Item { | |
String name(); | |
Packing packing(); | |
int price(); | |
} | |
interface Packing { | |
String pack(); | |
} | |
class Bottle implements Packing { | |
@Override | |
public String pack() { | |
return "Bottle"; | |
} | |
} | |
class Wrapper implements Packing { | |
@Override | |
public String pack() { | |
return "wrapper"; | |
} | |
} | |
abstract class Burger implements Item { | |
@Override | |
public Packing packing() { | |
return new Wrapper(); | |
} | |
} | |
abstract class ColdDrink implements Item { | |
@Override | |
public Packing packing() { | |
return new Bottle(); | |
} | |
} | |
class VegBurger extends Burger { | |
@Override | |
public String name() { | |
return "Veg Burger"; | |
} | |
@Override | |
public int price() { | |
return 15; | |
} | |
} | |
class ChickenBurger extends Burger { | |
@Override | |
public String name() { | |
return "Chicken Burger"; | |
} | |
@Override | |
public int price() { | |
return 25; | |
} | |
} | |
class Coke extends ColdDrink { | |
@Override | |
public String name() { | |
return "Coke"; | |
} | |
@Override | |
public int price() { | |
return 5; | |
} | |
} | |
class Fanta extends ColdDrink { | |
@Override | |
public String name() { | |
return "Fanta"; | |
} | |
@Override | |
public int price() { | |
return 4; | |
} | |
} | |
class Meal { | |
private List<Item> items = new ArrayList<Item>(); | |
public void addItem(Item item){ | |
items.add(item); | |
} | |
public float getCost(){ | |
int cost = 0; | |
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 { | |
static Meal prepareVegmeal() { | |
Meal vegMeal = new Meal(); | |
vegMeal.addItem(new VegBurger()); | |
vegMeal.addItem(new Fanta()); | |
return vegMeal; | |
} | |
static Meal prepareNonVegmeal() { | |
Meal nonVegMeal = new Meal(); | |
nonVegMeal.addItem(new ChickenBurger()); | |
nonVegMeal.addItem(new Coke()); | |
return nonVegMeal; | |
} | |
} | |
public class Main { | |
public static void main(String[] args) { | |
Meal nonVegMeal = MealBuilder.prepareNonVegmeal(); | |
nonVegMeal.showItems(); | |
Meal vegMeal = MealBuilder.prepareVegmeal(); | |
vegMeal.showItems(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment