Decorator pattern
The decorator adds new functionality to an existing object without altering its structure.
decorator vs inheritance
Yes, same thing can be achieved through inheritance, but
- adding new functionality to a given class hierarchy may explode class hierarchy
- inheritance not always possible, for example final classes in Java
- decorator can operate on any implementation of a given interface
- testability, you don't need test every subclass
- decorator pattern encourages developers to write code that adheres to the SOLID design principles
example
interface Shape {
void draw();
}
// draw any shape in frame
public class FrameShapeDecorator implements Shape {
private Shape shape;
// shape can be rectangle, circle and etc
public FrameShapeDecorator(Shape shape) {
this.shape = shape;
}
@Override
public void draw() {
shape.draw();
drawFrame();
}
// new functionality
private void drawFrame() {/* ... */}
}