# Decorator

In 
Published 2022-12-03

This tutorial explains to you the design pattern named Decorator (which is a Structural Pattern).

# Decorator Pattern - theory

Decorator design pattern in Java shows you how to add new functionality to an existing object without altering its structure. This pattern is used when you want to add functionality to a class without modifying that class.

Take a look at the following UML diagram representing the Decorator design pattern (for my example):

In Decorator Design Pattern, the main idea is to wrap a class and to add functionality to that class.

# Decorator Pattern - example

Here is that example using the Decorator Design Pattern in Java:

package decorator.java.example;
 
public interface Car {
     
    // This method build a car.
    public void build();
}
package decorator.java.example;
 
public class Chevrolet implements Car{
  
    public void build(){
        System.out.println("A Chevrolet car have been built.");
    }
     
}
package decorator.java.example;

public class BMW implements Car{

  public void build(){
    System.out.println("A BMW car have been built.");
  }

}
package decorator.java.example;
 
public abstract class CarDecorator implements Car{
     
    protected Car internalVariable;
     
    public CarDecorator(Car internalVariable){
          this.internalVariable = internalVariable;
    }
 
    public abstract void build();
 
}
package decorator.java.example;
 
public class PaintCar extends CarDecorator {
 
    public PaintCar(Car car) {
          super(car);       
       }
 
       @Override
       public void build() {
          System.out.println("----------------------------------"); 
          internalVariable.build();        
          paintCar();
       }
        
       private void paintCar(){
          System.out.println("This car have been painted as well.");
          System.out.println("----------------------------------");
       }
}
package decorator.java.example;
 
public class JavaDecoratorExampleMain {
     
   public static void main(String[] args) {
 
      Car car1 = new BMW();
      Car car2 = new Chevrolet();
 
      Car paintCar1 = new PaintCar(car1);
      paintCar1.build();
       
      Car paintCar2 = new PaintCar(car2);
      paintCar2.build();
       
   }
 
}

When you run this example you will receive the following result:

In my example the new functionality is to paint a car.