Wednesday 1 January 2014

Decorator Design pattern - Implementation [Dosa]



Click here to watch in Youtube : https://www.youtube.com/watch?v=x5mIx0Wq-nI


Click the below Image to Enlarge

Decorator Design pattern - Implementation [Dosa]


Decorator Design pattern - Implementation [Dosa] - Class Diagram




































Dosa.java

public interface Dosa
{
public String makeDosa();
}

PlainDosa.java

public class PlainDosa implements Dosa
{

@Override
public String makeDosa()
{
return "Plain Dosa ";
}
}

DosaDecorator.java

abstract class DosaDecorator implements Dosa
{

protected Dosa dosa;

public DosaDecorator( Dosa dosa )
{
this.dosa = dosa;
}

public String makeDosa()
{
return dosa.makeDosa();
}
}

MasalaDosaDecorator.java

public class MasalaDosaDecorator extends DosaDecorator
{

public MasalaDosaDecorator( Dosa dosa )
{
super(dosa);
}

public String makeDosa()
{
return dosa.makeDosa() + addMasala();
}

private String addMasala()
{
return ",Masala added";

}
}

OnionDosaDecorator.java

public class OnionDosaDecorator extends DosaDecorator
{

public OnionDosaDecorator( Dosa dosa )
{
super(dosa);
}

public String makeDosa()
{
return dosa.makeDosa() + addOnion();

}

private String addOnion()
{
return ",Onion added";
}
}

DecoratorClient.java

public class DecoratorClient
{

public static void main( String args[] )
{
PlainDosa plainDosaObj = new PlainDosa();
String plainDosa = plainDosaObj.makeDosa();
System.out.println(plainDosa);

String onionDosa = new OnionDosaDecorator(plainDosaObj).makeDosa();
System.out.println("\n'" + onionDosa + "' using OnionDosaDecorator");

String masalaDosa = new MasalaDosaDecorator(plainDosaObj).makeDosa();
System.out.println("\n'" + masalaDosa + "' using MasalaDosaDecorator");

}

}

Output

Plain Dosa 

'Plain Dosa ,Onion added' using OnionDosaDecorator

'Plain Dosa ,Masala added' using MasalaDosaDecorator

See also:

  • Decorator Design pattern - Introduction
  • Decorator Design pattern - Real Time Example [Dosa]
  • Decorator Design pattern - Real Time Example [Ice Cream]
  • Decorator Design pattern - Real Time Example [Pizza]
  • Decorator Design pattern - Real Time Example [Car]
  • Decorator Design pattern - Class Diagram
  • Decorator Design pattern - Sequence Diagram
  • Decorator Design pattern - Implementation [Pizza]
  • Decorator Design pattern - Implementation [Ice Cream]
  • Decorator Design pattern - Implementation [Car]
  • Decorator Design pattern - Implementation [Shape]
  • Decorator Design pattern - Key Points
  • All Design Patterns Links
  • No comments:

    Post a Comment