EDDYMENS

Last updated 2024-04-04 05:25:47

What Is A Decorator In Programming?

The term "decorator" is often used to describe a design pattern called the Decorator Pattern.

The Decorator Pattern allows behavior to be added to individual objects dynamically. It involves creating a set of classes that enhance the functionality of individual objects without affecting the behavior of other objects of the same class.

However, in Java, the Decorator Pattern is typically implemented using interfaces and inheritance rather than using language-specific syntax like decorators in Python.

Here's a conceptual example of the Decorator Pattern in Java:

01: // Component Interface 02: interface Pizza { 03: String getDescription(); 04: double getCost(); 05: } 06: 07: // Concrete Component 08: class PlainPizza implements Pizza { 09: public String getDescription() { 10: return "Plain Pizza"; 11: } 12: public double getCost() { 13: return 5.0; 14: } 15: } 16: 17: // Decorator 18: abstract class PizzaDecorator implements Pizza { 19: protected Pizza pizza; 20: public PizzaDecorator(Pizza pizza) { 21: this.pizza = pizza; 22: } 23: public String getDescription() { 24: return pizza.getDescription(); 25: } 26: public double getCost() { 27: return pizza.getCost(); 28: } 29: } 30: 31: // Concrete Decorator 32: class CheeseDecorator extends PizzaDecorator { 33: public CheeseDecorator(Pizza pizza) { 34: super(pizza); 35: } 36: public String getDescription() { 37: return pizza.getDescription() + ", Cheese"; 38: } 39: public double getCost() { 40: return pizza.getCost() + 1.5; 41: } 42: } 43: 44: // Usage 45: public class Main { 46: public static void main(String[] args) { 47: Pizza basicPizza = new PlainPizza(); 48: Pizza cheesePizza = new CheeseDecorator(basicPizza); 49: 50: System.out.println("Description: " + cheesePizza.getDescription()); 51: System.out.println("Cost: $" + cheesePizza.getCost()); 52: } 53: }

In this example:

  • Pizza is an interface defining the component behavior.
  • PlainPizza is a concrete implementation of the Pizza interface.
  • PizzaDecorator is an abstract class implementing the Pizza interface and acting as the base class for decorators.
  • CheeseDecorator is a concrete decorator adding functionality (cheese) to a Pizza.
  • The Main class demonstrates using the decorator pattern to add features (cheese) dynamically to a plain pizza object.

In a nutshell, decorators make it possible to attach additional behavior to existing behaviors.

Here is another article you might like 😊 "Diary Of Insights: A Documentation Of My Discoveries"