Decorator Pattern
The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
- Decorators have the same supertype as the objects they decorate.
- You can use one or more decorators to wrap an object.
- Given that the decorator has the same supertype as the object it decorates, we can pass around a decorated object in place of the original (wrapped) object.
- The decorator adds its own behavior either before and/or after delegating to the object it decorates to do the rest of the job.
- Objects can be decorated at any time, so we can decorate objects dynamically at runtime with as many decorators as we like.
Example
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 | public abstract class Item { public String name; public Item(){ name = "No Name"; } public String getName(){ return name; } public abstract int getCost(); } ========= public abstract class ItemDecorator extends Item { public abstract String getName(); } ========= public class Dinner extends Item{ Dinner(){ name = "Dinner"; } public String getName(){ return name; } @Override public int getCost() { return 110; } } ========== public class IceCream extends ItemDecorator{ Item item; IceCream(Item item){ this.item = item; } @Override public String getName() { return item.getName()+ " + Ice-Cream"; } @Override public int getCost() { return item.getCost() + 46; } } ========== public class Juice extends ItemDecorator{ Item item; Juice(Item item){ this.item = item; } @Override public String getName() { return item.getName()+" + Juice"; } @Override public int getCost() { return item.getCost() + 40; } } ========== public class DecoratorFlight { public static void main(String[] bag){ Item dinner = new Dinner(); dinner = new Juice(dinner); dinner = new IceCream(dinner); String names = dinner.getName(); int totalCost = dinner.getCost(); System.out.println(names+" = Rs: "+totalCost); } } |