-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecoratorDesignPattern.java
More file actions
67 lines (54 loc) · 1.55 KB
/
DecoratorDesignPattern.java
File metadata and controls
67 lines (54 loc) · 1.55 KB
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
// Step 1: The base interface
interface Coffee {
String getDescription();
int getCost();
}
// Step 2: Basic coffee class
class SimpleCoffee implements Coffee {
public String getDescription() {
return "Simple Coffee";
}
public int getCost() {
return 50;
}
}
// Step 3: Abstract decorator class
abstract class CoffeeDecorator implements Coffee {
protected Coffee coffee;
public CoffeeDecorator(Coffee coffee) {
this.coffee = coffee;
}
}
// Step 4: Concrete decorators
class MilkDecorator extends CoffeeDecorator {
public MilkDecorator(Coffee coffee) {
super(coffee);
}
public String getDescription() {
return coffee.getDescription() + ", Milk";
}
public int getCost() {
return coffee.getCost() + 10;
}
}
class SugarDecorator extends CoffeeDecorator {
public SugarDecorator(Coffee coffee) {
super(coffee);
}
public String getDescription() {
return coffee.getDescription() + ", Sugar";
}
public int getCost() {
return coffee.getCost() + 5;
}
}
// Client code
public class Main {
public static void main(String[] args) {
Coffee coffee = new SimpleCoffee(); // ₹50
coffee = new MilkDecorator(coffee); // ₹60
coffee = new SugarDecorator(coffee); // ₹65
System.out.println(coffee.getDescription()); // Output: Simple Coffee, Milk, Sugar
System.out.println("Cost: ₹" + coffee.getCost()); // Output: Cost: ₹65
}
}