In: Computer Science
Java Code. imagine you're working for a fast-food restaurant. get details returns name of the burger and getPrice return the price of the meal.
Using Decorator pattern make class BurgerToppings:
-Each topping is an extra $1 and the name provided in the constructor
-getTotalPrice: returns total price of burger + toppings
-getDetails: returns the burger name + name of topping with the word (extra)
Code:
public interface Burger{ double C(); String getDetails(); }
public class BigMac implements Burger{ private String order; private double price ; public BigMac() { this.order= "Big Mac"; this.price = 4.00; } @Override public double getPrice() { return price; } @Override public String getorder() { return name; } }
Output expected:
Ordering BigMac + extra pickles+ extra cheese
Total price = 6.0
CODE :
Burger.java
package c15;
public interface Burger{
double getPrice();
String getorder();
}
BurgerToppings.java
package c15;
public class BurgerToppings {
private String name;
BurgerToppings(String n){
name = n;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
BigMac.java
PROGRAM :
package c15;
import java.util.ArrayList;
public class BigMac implements Burger{
private String order;
private double price;
private ArrayList<BurgerToppings> toppings;
public BigMac() {
this.order= "Big Mac";
this.price = 4.00;
toppings = new ArrayList<BurgerToppings>();
}
void addTopping(String top) {
toppings.add(new BurgerToppings(top));
}
@Override
public double getPrice() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getorder() {
String topping="";
for(BurgerToppings t : toppings) {
topping += " Extra "+t.getName();
}
return order+topping;
}
public double getTotalPrice() {
double top=toppings.size();
return top+price;
}
public static void main(String[] args) {
BigMac mac = new BigMac();
mac.addTopping("Cheese");
mac.addTopping("pickles");
System.out.println("Ordering "+mac.getorder());
System.out.println("Total price = "+mac.getTotalPrice());
}
}
OUTPUT :
Ordering Big Mac Extra Cheeese Extra PiCkles
Total Price = 6.0