The Decorator pattern in C# is a design pattern that enables the dynamic addition of additional functionality to an object without altering its original behavior. It is used to increase a class’s capabilities at runtime without changing the original code.
The Decorator pattern can be implemented in C# by first defining a base class that specifies an object’s fundamental functionality, followed by decorator classes that extend the base class with new functionality. The decorators and base class can be used interchangeably because they both implement the same interface.
Consider the case where we have a base class called ICar that outlines the essential features of a car, such as its description and cost. Then, we can make a concrete class called BasicCar that implements this interface and has a straightforward description and cost. Next, a CarDecorator abstract class that implements the ICar interface and has a reference to an ICar object can be constructed. By using this abstract class, we may build concrete decorator classes that give the car new features, like leather seats or a sunroof.
Here is an example of how to apply this pattern in C#:
// Define the base component
public interface ICar
{
string Description { get; }
double Price { get; }
}
// Define the concrete component
public class BasicCar: ICar
{
public string Description { get { return "Basic car"; } }
public double Price { get { return 10000.00; } }
}
// Define the decorator
public abstract class CarDecorator : ICar
{
private ICar _car;
public CarDecorator(ICar car)
{
_car = car;
}
public virtual string Description { get { return _car.Description; } }
public virtual double Price { get { return _car.Price; } }
}
// Define the concrete decorator
public class LeatherSeats : CarDecorator
{
public LeatherSeats(ICar car) : base(car) { }
public override string Description { get { return base.Description + ", leather seats"; } }
public override double Price { get { return base.Price + 2000.00; } }
}
// Usage
ICar myCar = new BasicCar(); // create the basic car
myCar = new LeatherSeats(myCar); // add leather seats
Console.WriteLine("Description: {0}, Price: {1}", myCar.Description, myCar.Price);
If you have skills in PHP programming and you want to enhance your career in this field, a PHP certification from StudySection can help you reach your desired goals. Both beginner level and expert level PHP Certification Exams are offered by StudySection along with other programming certification exams.