In: Computer Science
Java Code.
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 -

BigMac -

BurgerWithToppings -

BigMacWithToppings -

Main -

OUTPUT :-

TEXT CODE :-
Burger -
public interface Burger {
double getPrice();
String getOrder();
}
BigMac -
public class BigMac implements Burger {
private String order;
private double price;
public BigMac() {
this.order = "Big Mac";
this.price = 4.00;
}
// Method C
@Override
public double getPrice() {
return price;
}
// Method getDetails
@Override
public String getOrder() {
return order;
}
}
BurgerWithToppings -
public abstract class BurgerWithToppings implements Burger
{
protected Burger burger;
public BurgerWithToppings(Burger b) {
this.burger = b;
}
@Override
public double getPrice() {
return burger.getPrice();
}
@Override
public String getOrder() {
return burger.getOrder();
}
}
BigMacWithToppings -
public class BigMacWithToppings extends BurgerWithToppings
{
private String toppings[];
public BigMacWithToppings(BigMac bm,String[] toppings)
{
super(bm);
this.toppings = toppings;
}
@Override
public double getPrice() {
double tempPrice =
super.getPrice();
for(int i =0; i <
this.toppings.length; i++) {
tempPrice++;
}
return tempPrice;
}
@Override
public String getOrder() {
String tempName =
super.getOrder();
for(String t : this.toppings)
{
tempName += " +
extra "+t;
}
return tempName;
}
}
Main -
public class Main {
public static void main(String[] args) {
String toppings[] = {"pickles",
"cheese"};
Burger burgWidTop = new
BigMacWithToppings(new BigMac(),toppings);
System.out.println("Ordering
"+burgWidTop.getOrder());
System.out.println("Total Price =
"+burgWidTop.getPrice());
}
}