Skip to main content

Command Palette

Search for a command to run...

Yoda and the Decorator Pattern: A Lesson for Luke

Published
•1 min read
Yoda and the Decorator Pattern: A Lesson for Luke

// Base class
public abstract class Lightsaber
{
    public abstract void Assemble();
}

// Concrete implementation of the base class
public class StandardLightsaber : Lightsaber
{
    public override void Assemble()
    {
        Console.WriteLine("Assembling standard lightsaber");
    }
}

// Decorator class
public class HiltDesignDecorator : Lightsaber
{
    private Lightsaber _lightsaber;
    private string _hiltDesign;

    public HiltDesignDecorator(Lightsaber lightsaber, string hiltDesign)
    {
        _lightsaber = lightsaber;
        _hiltDesign = hiltDesign;
    }

    public override void Assemble()
    {
        _lightsaber.Assemble();
        Console.WriteLine($"Adding {_hiltDesign} hilt design to lightsaber");
    }
}

// Decorator class
public class BladeColorDecorator : Lightsaber
{
    private Lightsaber _lightsaber;
    private string _bladeColor;

    public BladeColorDecorator(Lightsaber lightsaber, string bladeColor)
    {
        _lightsaber = lightsaber;
        _bladeColor = bladeColor;
    }

    public override void Assemble()
    {
        _lightsaber.Assemble();
        Console.WriteLine($"Adding {_bladeColor} blade color to lightsaber");
    }
}

Then, you can use the decorator classes to create customized lightsabers:

Lightsaber lightsaber = new HiltDesignDecorator(new BladeColorDecorator(new StandardLightsaber(), "green"), "gold");
lightsaber.Assemble();

This would output:

Assembling standard lightsaber
Adding green blade color to lightsaber
Adding gold hilt design to lightsaber

If you liked my content, do kindly like and share in your network. And don't forget to subscribe to the newsletter to NEVER miss an article. Please follow me on twitter.

More from this blog

I am Zahiruddin Tavargere (Zahere). A social-learner, here to learn, share and grow with the tech community.

74 posts

I am Zahiruddin Tavargere (Zahere). A firm believer in social learning, I owe my dev career to all the tech content creators I have learned from - this is my contribution back to the community.