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
No comments:
Post a Comment