Decorator Design Pattern

Decorator Design Pattern.


Decorator Design Pattern allows class to extend its functionalities dynamically without changing the actual class implementation.


Decorator Design Pattern Example In Java.

Say we are opening a Cake shop and planning to sell many flavours of cake.
Also, custom cake order will be accepted as per Customer needs. 
How to design a class for this purpose. Decorator pattern is helpful for this kind of requirement.


Cake.java
interface Cake{
 void flavour();
 int getAmount();
}
BasicCake.java
class BasicCake implements Cake{
 @Override
 public void flavour() {
  System.out.println("Basic Cake");
 }

 @Override
 public int getAmount() {
  return 50;
 }
}
CakeDecorator.java (It is made abstract because it is helper class and object of only implementations of it is possible)
abstract class CakeDecorator implements Cake{
 private Cake cake;
 
 public CakeDecorator(Cake cake) {
  this.cake = cake;
 }
 
 @Override
 public void flavour() {
  cake.flavour();
 }
 
 @Override
 public int getAmount() {
  return cake.getAmount();
 }
}
VanillaCake.java
class VanillaCake extends CakeDecorator{
 
 public VanillaCake(Cake cake) {
  super(cake);
 }
 
 @Override
 public void flavour() {
  super.flavour();
  System.out.println("Adding Vanilla falvour");
 }
 
 @Override
 public int getAmount() {
  return super.getAmount() + 10;
 }
}
StrawberyCake.java
class StrawberyCake extends CakeDecorator{
 
 public StrawberyCake(Cake cake) {
  super(cake);
 }
 
 @Override
 public void flavour() {
  super.flavour();
  System.out.println("Adding Strawberry falvour");
 }
 
 @Override
 public int getAmount() {
  return super.getAmount() + 10;
 }
}
DecoratorDesignPattern.java
public class DecoratorDesignPattern {

 public static void main(String[] args) {
  VanillaCake vanillaStrawberryCake = new VanillaCake(new StrawberyCake(new BasicCake()));
  vanillaStrawberryCake.flavour();
  System.out.println(vanillaStrawberryCake.getAmount());
 }
}


Decorator Design Pattern used in JDK API.


Base class
java.io.Reader;
java.io.InputStream;

Decorators:
java.io.BufferedReader(java.io.Reader);
java.io.FileReader(java.io.Reader);

java.io.DataInputStream(
java.io.InputStream)
java.io.BufferedInputStream
(java.io.InputStream)  

Constructor of BufferedReader takes parameter as Reader class and add more few more features like readLine() method, which is specific to BufferedReader class only.

Eg:  BufferedReader in = new BufferedReader(new FileReader("foo.in"));
Eg:  DataInputStream input = new DataInputStream(new ZipInputStream(new

        FileInputStream("foo.zip")));
 

You may also like to see


Observer Design Pattern

Adapter Design Pattern

Command Design Pattern

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Post a Comment