Decorator

Using the decorator design pattern is fairly simple. You can have a base class with methods and properties that are present when you make a new object with the class. Now say you have some instances of the class that need methods or properties that didn't come from the base class. You can add those extra methods and properties to the base class, but that could mess up your other instances. You could even make subclasses to hold specific methods and properties you need that you can't put in your base class.

Either of those approaches will solve your problem, but they are clunky and inefficient. That's where the decorator pattern steps in. Instead of making your code base ugly just to add a few things to an object instance, you can tack on those specific things directly to the instance. So if you need to add a new property that holds the time for an instance, you can use the decorator pattern to add it directly to that particular instance and it won't affect any other instances of that class object.

Have you ever ordered food online? Then you've probably encountered the decorator pattern. If you're getting a sandwich and you want to add special toppings, the website isn't adding those toppings to every sandwich every current user is trying to order. It just adds those special toppings to your instance of that sandwich. When you need to work with multiple instances of an object that need values added dynamically like this, the decorator pattern is a good option.

Last updated

Was this helpful?