Decorator Pattern

Introduction and implementation of decorator design pattern


Category: Design Patterns Tags: C#

Decorator Design Pattern - Code Files

Introduction

    Decorator design pattern is a structural design pattern which is used to add new behaviors to object by placing object in a wrapper that is called decorator. Decorator is responsible of adding new behaviors.

Suppose you want to build different cars so you have created classes called SUV and Sedan but later you want to color these cars and to add this additional behavior we can make use of decorators without changing existing car classes. Let's check how that is done in Implementation section.

Implementation

    We are having car classes as following.

public interface ICar
{
    void Build();
}

public class Sedan : ICar
{
    public void Build()
    {
        Console.WriteLine($"Build {this.GetType().Name}");
    }
}

public class SUV : ICar
{
    public void Build()
    {
        Console.WriteLine($"Build {this.GetType().Name}");
    }
}

Above ICar.Build basically builds any car Sedan or SUV. Now to paint the car we can use decorators without modifying above classes. Decorator basically extends ICar and also abstracts the ICar object.

public class CarDecorator : ICar
{
    protected ICar _car;

    public CarDecorator(ICar car)
    {
        _car = car;
    }

    public virtual void Build()
    {
        _car.Build();
    }
}

public class RedCarDecorator : CarDecorator
{
    public RedCarDecorator(ICar car) : base(car)
    {
        _car = car;
    }

    public override void Build()
    {
        _car.Build();
        Console.WriteLine("Paint red");
    }
}

RedCarDecorator can build any car (i.e. Sedan or SUV) and later apply red color on that. Let's try out decorators.

//red sedan
ICar car = new Sedan();
CarDecorator carDecorator = new RedCarDecorator(car);
carDecorator.Build();


//red suv
car = new SUV();
carDecorator = new RedCarDecorator(car);
carDecorator.Build();

Output

Build Sedan

Paint red

Build SUV

Paint red

 


Like 0 People
Last modified on 18 October 2022
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 164
Questions: 16
Given Best Solutions: 16 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x