Decorate


The Decorator pattern is used to enhance an existing object dynamically with additional functions or variables. By doing so one literally "decorates" an object.


Imagine you have a class named "Car". It has a moving, parking and a braking function.
Later you decide that it should also have an on-board camera system and it should be able to monitor the rear of the vehicle for the case of parking backwards like it exists in some advanced cars e.g. Lamborghinis.


On-board monitor inside a Lamborghini.

Instead of rewriting the class you can just write a decorator class which has to implement an interface which the original "Car" class also should have. This interface would contain a function declaration for parking.

Then you would have to implement this function for parking inside the decorator and add the monitoring code to it.

Now, when you create a new "Car" instance and wrap it with a decorator instance, you would automatically execute the camera monitoring code by calling parking function on this decorator instance.


C# example:

  				
using System;
namespace Decorator
{
  public class DecoratorPattern {
    interface ICar {
      void park();
    }

    class Car: ICar {
      public void park(){
        Console.WriteLine("car is parking ...");
      }

      public void move(){
        Console.WriteLine("car is moving ...");
      }

      public void brake()
      {
        Console.WriteLine("car is braking ...");
      }
    }

    class DecoratorParkingCamera: ICar {
      ICar car;

      public DecoratorParkingCamera(ICar c) {
        car = c;
      }

      public void park() {
        car.park();
        Console.WriteLine("and camera is monitoring ...");
      }
    }

    class MainClass {

      public static void Main() {
        Car car = new Car();
        car.move();
        car.brake();
        car.park();

        Console.WriteLine("\n");

        // Adding decorator dynamically
        DecoratorParkingCamera decoratedcar = new DecoratorParkingCamera(car);
        decoratedcar.park();
      }
    }
  }
}

  				
  				
  				


Console output:

car is moving ...
car is braking ...
car is parking ...


car is parking ...
and camera is monitoring ...