Reputation: 2409
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.
Upvotes: 0
Views: 456
Reputation: 308061
It is a decorator pattern, but as Finbarr noted, it's a bit messy:
floppyConcreteDeco
(which should be named starting with a capital letter) and/or AccessoryDecorator
should extend ComputerComponent
, however.
The reason is that the you'll want to use the decorator object the same way you use a "normal" ComputerComponent
and you can't really do that unless you have a common base class or a common interface.
Upvotes: 1
Reputation: 32126
This is indeed the Decorator design pattern, albeit a bit of a messy example.
Upvotes: 1
Reputation: 1200
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()}.
Upvotes: 1