I’ve an example please tell me whether it is Decorator pattern or not?
public abstract class ComputerComponent
{
String description ="Unknown Type";
public String getDescription()
{
return description;
}
public abstract double getCost();
}
public abstract class AccessoryDecorator
{
ComputerComponent comp;
public abstract String getDescription();
}
public class PIIIConcreteComp extends ComputerComponent
{
public PIIIConcreteComp()
{
description= "Pentium III";
}
public double getCost()
{
return 19950.00;
}
}
public class floppyConcreteDeco extends AccessoryDecorator
{
public floppyConcreteDeco(ComputerComponent comp)
{
this.comp=comp;
}
public String getDescription()
{
return comp.getDescription() +", floppy 1.44 mb";
}
public double getCost()
{
return 250+comp.getCost();
}
}
public class ComponentAssembly
{
public static void createComponent()
{
ComputerComponent comp = new PIIConcreteComp();
// create a PIII computer object
ComputerComponent deco1= new floppyConcreteDeco(comp);
// decorate it with a floppy
//ComputerComponent deco2= newCDRomConcreteDeco(deco1);
ComputerComponent deco2= new floppyConcreteDeco(deco1);
// decorate with a CDRom or with one more floppy
System.out.println( deco2.getdescription() + " " + deco2.getCost());
}
}
Thank you.
Your point is good, but your code wouldn’t even compile, mainly because ComputerComponent has to be interface which has to be implemented by AccessoryDecorator and PIIIConcreteComp (and your braces are terribly messed, by the way). Usually AccessoryDecorator would also implement “default” implementation of it’s methods like getDescription() {return comp.getDescription()}.