Skip to main content

Yoda and the Decorator Pattern: A Lesson for Luke

Updated 1 min readMarkdown
Part of seriesSoftware Development and System Design
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.

About the author

  • I am a Journalist-turned-Software Engineer. I love coding and the associated grind of learning every day. 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.

No comments yet. Be the first to comment.

More from this blog