The Decorator pattern allows you to dynamically add additional behavior or features to an object at runtime. In the context of a car, let’s create an example with a base Car
class, a SportsCar
class, and a LuxuryCar
class. We’ll use decorators to add extra features to the cars.
First, let’s define the base Car
class:
public interface ICar
{
string GetDescription();
double GetCost();
}
public class Car : ICar
{
public string GetDescription()
{
return "Basic Car";
}
public double GetCost()
{
return 20000.0;
}
}
Next, we’ll create the SportsCar
class, which will act as a decorator and add sports car features:
public class SportsCar : ICar
{
private readonly ICar _car;
public SportsCar(ICar car)
{
_car = car;
}
public string GetDescription()
{
return _car.GetDescription() + ", Sports Car";
}
public double GetCost()
{
return _car.GetCost() + 15000.0;
}
}
Now, let’s create the LuxuryCar
class, which will be another decorator to add luxury features:
public class LuxuryCar : ICar
{
private readonly ICar _car;
public LuxuryCar(ICar car)
{
_car = car;
}
public string GetDescription()
{
return _car.GetDescription() + ", Luxury Car";
}
public double GetCost()
{
return _car.GetCost() + 30000.0;
}
}
Finally, we can use the decorators to create different car configurations:
// Creating a basic car
ICar basicCar = new Car();
Console.WriteLine("Description: " + basicCar.GetDescription());
Console.WriteLine("Cost: $" + basicCar.GetCost());
// Adding sports car features to the basic car
ICar sportsCar = new SportsCar(basicCar);
Console.WriteLine("Description: " + sportsCar.GetDescription());
Console.WriteLine("Cost: $" + sportsCar.GetCost());
// Adding luxury features to the sports car
ICar luxuryCar = new LuxuryCar(sportsCar);
Console.WriteLine("Description: " + luxuryCar.GetDescription());
Console.WriteLine("Cost: $" + luxuryCar.GetCost());
Output:
Description: Basic Car
Cost: $20000
Description: Basic Car, Sports Car
Cost: $35000
Description: Basic Car, Sports Car, Luxury Car
Cost: $65000