Click here to watch in Youtube : https://www.youtube.com/watch?v=-CSs47U8H4k
Click the below Image to Enlarge
Decorator Design pattern - Implementation [Ice Cream] - Class Diagram |
Icecream.java
public interface Icecream
{
public String makeIcecream();
}
VanillaIcecream.java
public class VanillaIcecream implements Icecream
{
@Override
public String makeIcecream()
{
return "Vanilla Icecream";
}
}
IcecreamDecorator.java
abstract class IcecreamDecorator implements Icecream
{
protected Icecream specialVanillaIcecream;
public IcecreamDecorator( Icecream specialVanillaIcecream )
{
this.specialVanillaIcecream = specialVanillaIcecream;
}
public String makeIcecream()
{
return specialVanillaIcecream.makeIcecream();
}
}
ChocolateDecorator.java
public class ChocolateDecorator extends IcecreamDecorator
{
public ChocolateDecorator( Icecream specialIcecream )
{
super(specialIcecream);
}
public String makeIcecream()
{
return specialVanillaIcecream.makeIcecream() + addChocolate();
}
private String addChocolate()
{
return " + with chocolate";
}
}
NuttyDecorator.java
public class NuttyDecorator extends IcecreamDecorator
{
public NuttyDecorator( Icecream specialVanillaIcecream )
{
super(specialVanillaIcecream);
}
public String makeIcecream()
{
return specialVanillaIcecream.makeIcecream() + addNuts();
}
private String addNuts()
{
return " + with nuts";
}
}
DecoratorClient.java
public class DecoratorClient
{
public static void main( String args[] )
{
VanillaIcecream vanillaIcecreamObj = new VanillaIcecream();
String vanillaIcecream = vanillaIcecreamObj.makeIcecream();
System.out.println(vanillaIcecream);
String vanillaIcecreamWithNuts=new NuttyDecorator(vanillaIcecreamObj).makeIcecream();
System.out.println("\n'"+vanillaIcecreamWithNuts + "' is prepared using NuttyDecorator");
String vanillaIcecreamWithChocalate=new ChocolateDecorator(vanillaIcecreamObj).makeIcecream();
System.out.println("\n'"+vanillaIcecreamWithChocalate+ "' is prepared using ChocolateDecorator");
String vanillaIcecreamWithChocalateAndNuts=new NuttyDecorator(new ChocolateDecorator(vanillaIcecreamObj)).makeIcecream();
System.out.println("\n'"+vanillaIcecreamWithChocalateAndNuts+ "' is prepared using ChocolateDecorator and NuttyDecorator");
}
}
Output
Vanilla Icecream
'Vanilla Icecream + with nuts' is prepared using NuttyDecorator
'Vanilla Icecream + with chocolate' is prepared using ChocolateDecorator
'Vanilla Icecream + with chocolate + with nuts' is prepared using ChocolateDecorator and NuttyDecorator
No comments:
Post a Comment