Sunday, 5 January 2014

Decorator Design pattern - Implementation [Car]

🚗 Master Java Design Patterns & Architecture!

Enjoying this step-by-step breakdown? Subscribe to Ram N Java for clean code, practical implementations, and real-world software design tutorials.

🔔 Subscribe to Ram N Java

Understanding the Decorator Design Pattern

The Decorator Pattern is a structural design pattern that allows you to dynamically attach additional responsibilities or behaviors to an object at runtime.

Rather than modifying original source code or using excessive inheritance, this pattern wraps an existing object with dedicated decorator classes using object composition.

Real-World Scenario: Customizing Cars Dynamically

Consider manufacturing a car. Initially, the core car assembly produces a base vehicle (doors, wheels, body, and glass) without a specific engine attached.

Depending on customer demand, that car needs to be equipped with either a Petrol Engine or a Diesel Engine. Creating separate fixed classes like PetrolBMWCar and DieselBMWCar creates tight coupling and code duplication.

By introducing a CarDecorator, we can take a base car and decorate it dynamically with the required engine type.

Step-by-Step Code Walkthrough

1. Component Interface

Define the core contract that both the basic car and decorators will share:

public interface Car {
    void manufactureCar();
}

2. Concrete Component

Create the basic car implementation without any engine attached:

public class BMWCar implements Car {
    @Override
    public void manufactureCar() {
        System.out.println("Manufacturing base BMW: Body, Doors, Wheels, Glass added.");
    }
}

3. Abstract Decorator

The decorator implements Car and maintains a reference to the wrapped Car instance:

public abstract class CarDecorator implements Car {
    protected Car car;

    public CarDecorator(Car car) {
        this.car = car;
    }

    @Override
    public void manufactureCar() {
        car.manufactureCar();
    }
}

4. Concrete Decorators

Create specialized decorators that attach specific engine features to the car:

public class DieselCarDecorator extends CarDecorator {
    public DieselCarDecorator(Car car) {
        super(car);
    }

    @Override
    public void manufactureCar() {
        super.manufactureCar();
        addDieselEngine();
    }

    private void addDieselEngine() {
        System.out.println("Added: Diesel Engine installed.");
    }
}

public class PetrolCarDecorator extends CarDecorator {
    public PetrolCarDecorator(Car car) {
        super(car);
    }

    @Override
    public void manufactureCar() {
        super.manufactureCar();
        addPetrolEngine();
    }

    private void addPetrolEngine() {
        System.out.println("Added: Petrol Engine installed.");
    }
}

Key Advantages of This Approach

  • Runtime Customization: Behaviors can be added or swapped dynamically without rebuilding the core structure.
  • Open/Closed Principle: Add new engines or vehicle features without altering existing base car code.
  • Composition Over Inheritance: Prevents an explosion of subclasses for different feature combinations.

Related Tutorials You Might Like

Continue exploring core design patterns with these hands-on tutorials:



Click here to watch in Youtube : https://www.youtube.com/watch?v=bmVLHsH2QoQ

Click the below Image to Enlarge

Decorator Design pattern - Implementation [Car]


Decorator Design pattern - Implementation [Car] - Class Diagram























Car.java

public interface Car
{
public Car manufactureCar();
}

BMWCar.java

public class BMWCar implements Car
{

private final String CARNAME = "BMW";
private String       carBody;
private String       carDoor;
private String       carWheels;
private String       carGlass;
private String       engine;

public String getCarBody()
{
return carBody;
}

public void setCarBody( String carBody )
{
this.carBody = carBody;
}

public String getCarDoor()
{
return carDoor;
}

public void setCarDoor( String carDoor )
{
this.carDoor = carDoor;
}

public String getCarWheels()
{
return carWheels;
}

public void setCarWheels( String carWheels )
{
this.carWheels = carWheels;
}

public String getCarGlass()
{
return carGlass;
}

public void setCarGlass( String carGlass )
{
this.carGlass = carGlass;
}

public String getCARNAME()
{
return CARNAME;
}

public String getEngine()
{
return engine;
}

public void setEngine( String engine )
{
this.engine = engine;
}

@Override
public String toString()
{
return "BMWCar [CARNAME=" + CARNAME + ", carBody=" + carBody + ", carDoor=" + carDoor + ", carWheels="
               + carWheels + ", carGlass=" + carGlass + ", engine=" + engine + "]";
}

@Override
public Car manufactureCar()
{
this.carBody = "carbon fiber material";
this.carDoor = "4 car doors";
this.carGlass = "6 car glasses";
this.carWheels = "4 MRF wheels";
return this;
}
}

CarDecorator.java

public abstract class CarDecorator implements Car
{
Car car;

public CarDecorator( Car car )
{
super();
this.car = car;
}

public Car manufactureCar()
{
return car.manufactureCar();
}
}

DieselCarDecorator.java

public class DieselCarDecorator extends CarDecorator
{

public DieselCarDecorator( Car car )
{
super(car);

}

public Car manufactureCar()
{
car.manufactureCar();
addEngine(car);
return car;
}

public void addEngine( Car car )
{
if( car instanceof BMWCar )
{
BMWCar BMWCar = (BMWCar) car;
BMWCar.setEngine("Diesel Engine");
System.out.println("DieselCarDecorator added Diesel Engine to the Car : " + car);
}

}
}

PetrolCarDecorator.java

public class PetrolCarDecorator extends CarDecorator
{

public PetrolCarDecorator( Car car )
{
super(car);
}
public Car manufactureCar()
{
car.manufactureCar();
addEngine(car);
return car;
}

public void addEngine( Car car )
{
if( car instanceof BMWCar )
{
BMWCar BMWCar = (BMWCar) car;
BMWCar.setEngine("Petrol Engine");
System.out.println("PetrolEngineDecorator added Petrol Engine to the Car : " + car);
}

}
}

DecoratorClient.java

public class DecoratorClient
{

public static void main( String[] args )
{
Car bmwCar1 = new BMWCar();
System.out.println(bmwCar1+"\n");

DieselCarDecorator carWithDieselEngine = new DieselCarDecorator(bmwCar1);
carWithDieselEngine.manufactureCar();

System.out.println("\n*******************************************************");

Car bmwCar2 = new BMWCar();

PetrolCarDecorator carWithPetrolEngine = new PetrolCarDecorator(bmwCar2);
carWithPetrolEngine.manufactureCar();

}
}

Output

BMWCar [CARNAME=BMW, carBody=null, carDoor=null, carWheels=null, carGlass=null, engine=null]

DieselCarDecorator added Diesel Engine to the Car : BMWCar [CARNAME=BMW, carBody=carbon fiber material, carDoor=4 car doors, carWheels=4 MRF wheels, carGlass=6 car glasses, engine=Diesel Engine]

*******************************************************
PetrolEngineDecorator added Petrol Engine to the Car : BMWCar [CARNAME=BMW, carBody=carbon fiber material, carDoor=4 car doors, carWheels=4 MRF wheels, carGlass=6 car glasses, engine=Petrol Engine]


See also:

  • Decorator Design pattern - Introduction
  • Decorator Design pattern - Real Time Example [Dosa]
  • Decorator Design pattern - Real Time Example [Ice Cream]
  • Decorator Design pattern - Real Time Example [Pizza]
  • Decorator Design pattern - Real Time Example [Car]
  • Decorator Design pattern - Class Diagram
  • Decorator Design pattern - Sequence Diagram
  • Decorator Design pattern - Implementation [Dosa]
  • Decorator Design pattern - Implementation [Pizza]
  • Decorator Design pattern - Implementation [Ice Cream]
  • Decorator Design pattern - Implementation [Shape]
  • Decorator Design pattern - Key Points
  • All Design Patterns Links
  • No comments:

    Post a Comment

    Tutorials