Decorator Patten is a Structural Patter. i.e It talks about how to structure your classes.
Decorator pattern just decorates the pre-existing class. So that we do not have the change the class that we are trying to decorate.
interface Shape{
public void draw();
}
abstract class ShapeDecorator implements Shape{
protected Shape targetObject;
public ShapeDecorator(Shape targetToDecorate){
targetObject = targetToDecorate;
}
@Override
public void onDraw(){
targetObject.draw();
}
}
So now we can have RedShapeDecorator or BlueShapeDecorator concrete classes which will override onDraw(), call super and do more stuff to it, to decorate.
class RedShapeDecorator extends ShapeDecorator{
public RedShareDecorator(Share target){
super(target);
}
@Override
public void draw(){
super.draw();
target.setBorderColor("red");
}
}
Client will use it like.
Shape shape = new Circle();
Shape redDecor = new RedShapeDecorator(shape);
redDecor.draw();
Decorator pattern just decorates the pre-existing class. So that we do not have the change the class that we are trying to decorate.
interface Shape{
public void draw();
}
abstract class ShapeDecorator implements Shape{
protected Shape targetObject;
public ShapeDecorator(Shape targetToDecorate){
targetObject = targetToDecorate;
}
@Override
public void onDraw(){
targetObject.draw();
}
}
So now we can have RedShapeDecorator or BlueShapeDecorator concrete classes which will override onDraw(), call super and do more stuff to it, to decorate.
class RedShapeDecorator extends ShapeDecorator{
public RedShareDecorator(Share target){
super(target);
}
@Override
public void draw(){
super.draw();
target.setBorderColor("red");
}
}
Client will use it like.
Shape shape = new Circle();
Shape redDecor = new RedShapeDecorator(shape);
redDecor.draw();