Decorator Design Pattern is a Structural Design Pattern that adds additional behavior or responsibilities to an object at runtime.
Intention
- Adds additional functionality to an object at runtime.
- Provides flexible alternative to sub classing.
- Works as a filter by applying criteria.
Component - Interface for objects that can have additional responsibilities at runtime.
Concrete Components - Objects that are wrapped by additional behavior.
Decorator - Type of additional behavior that will wrap around Concrete Components
Concrete Decorators - Extends the functionality of the component by adding behavior or features.
Client - The user who needs the Concrete Components to be added new responsibilities.
Component
public interface Vehicle {
public void drive();
}
Concrete Components
public class Car implements Vehicle {
@Override
public void drive() {
System.out.println("Drive with fuel");
}
}
Decorator
public abstract class FuelDecorator implements Vehicle {
protected Vehicle vehicle;
public FuelDecorator(Vehicle vehicle) {
this.vehicle = vehicle;
}
@Override
public abstract void drive();
}
Concrete Decorators
public class HybridType extends FuelDecorator {
@Override
public void drive() {
vehicle.drive();
System.out.println("and Battery");
}
public HybridType(Vehicle vehicle) {
super(vehicle);
}
}
Client
public class Client {
public static void main(String[] args) {
Vehicle vehicle = new Car();
vehicle.drive(); // Output: Drive with fuel
Vehicle hybridCar = new HybridType(vehicle);
hybridCar.drive(); // Output: Drive with fuel
// and Battery
}
}
No comments:
Post a Comment