Open In App

Decorator Method – Python Design Patterns

Last Updated : 06 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Decorator Method is a Structural Design Pattern which allows you to dynamically attach new behaviors to objects without changing their implementation by placing these objects inside the wrapper objects that contains the behaviors. 
It is much easier to implement Decorator Method in Python because of its built-in feature. It is not equivalent to the Inheritance because the new feature is added only to that particular object, not to the entire subclass.
 

Problem Without Using Decorator Method


Imagine We are working with a formatting tool that provides features likes Bold the text and Underlines the text. But after some time, our formatting tools got famous among the targeted audience and on taking the feedback we got that our audience wants more features in the application such as making the text Italic and many other features. 
Looks Simple? It’s not the easy task to implement this or to extend our classes to add more functionalities without disturbing the existing client code because we have to maintain the Single Responsibility Principle.
 

Solution Using Decorator Method


Now let’s look at the solution that we have to avoid such conditions. Initially, we have only WrittenText but we have to apply filters like BOLD, ITALIC, UNDERLINE. So, we will create separate wrapper classes for each function like BoldWrapperClass, ItalicWrapperClass, and UnderlineWrapperclass.
 

Decorator-Written-Text

Decorator-Written-Text


First, we will call BoldWrapperclass over the Written text which ultimately converts the text into BOLD letters
 

Decorator-Wrapper

Decorator-Wrapper


Then we will apply the ItalicWrapperClass and UnderlineWrapperClass over the Bold text which will give us the result what we want.
 

Decorator-Underline

Decorator-Underline


Following Code is written using Decorator Method: 
 

Python
class WrittenText:

    """Represents a Written text """

    def __init__(self, text):
        self._text = text

    def render(self):
        return self._text

class UnderlineWrapper(WrittenText):

    """Wraps a tag in <u>"""

    def __init__(self, wrapped):
        self._wrapped = wrapped

    def render(self):
        return "<u>{}</u>".format(self._wrapped.render())

class ItalicWrapper(WrittenText):

    """Wraps a tag in <i>"""

    def __init__(self, wrapped):
        self._wrapped = wrapped

    def render(self):
        return "<i>{}</i>".format(self._wrapped.render())

class BoldWrapper(WrittenText):

    """Wraps a tag in <b>"""

    def __init__(self, wrapped):
        self._wrapped = wrapped

    def render(self):
        return "<b>{}</b>".format(self._wrapped.render())

""" main method """

if __name__ == '__main__':

    before_gfg = WrittenText("GeeksforGeeks")
    after_gfg = ItalicWrapper(UnderlineWrapper(BoldWrapper(before_gfg)))

    print("before :", before_gfg.render())
    print("after :", after_gfg.render())

Class-Diagram for Decorator Method

Following is the class diagram for Decorator Method: 
 

Decorator-Class-diagram

Decorator-Class-Diagram


 

Advantages


 

  • Single Responsibility Principle: It is easy to divide a monolithic class which implements many possible variants of behavior into several classes using the Decorator method.
  • Runtime Responsibilities: We can easily add or remove the responsibilities from an object at runtime.
  • SubClassing: The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at runtime for individual objects.


 

Disadvantages


 

  1. removing Wrapper: It is very hard to remove a particular wrapper from the wrappers stack.
  2. Complicated Decorators: It can be complicated to have decorators keep track of other decorators, because to look back into multiple layers of the decorator chain starts to push the decorator pattern beyond its true intent.
  3. Ugly Configuration: Large number of code of layers might make the configurations ugly.


 

Applicability


 

  1. Incapable Inheritance: Generally, Decorator method is used when it is not possible to extend the behavior of an object using the Inheritance.
  2. Runtime Assignment: One of the most important feature of Decorator method is to assign different and unique behaviors to the object at the Runtime.


Further Read – Decorator Design Pattern in Java
 



Previous Article
Next Article

Similar Reads

Introduction to Decorator Pattern in C++ | Design Patterns
The Decorator Pattern is a structural design pattern in software engineering that enables the dynamic addition of new behaviors or responsibilities to individual objects without altering their underlying class structure. It achieves this by creating a set of decorator classes that are used to wrap concrete components, which represent the core funct
12 min read
Difference Between the Facade, Proxy, Adapter, and Decorator Design Patterns
Understanding design patterns is crucial for software developers. Facade, Proxy, Adapter, and Decorator are key patterns that address different aspects of software design, from simplifying interfaces to enhancing functionality. This article explores their distinctions and practical applications in software development. Important Topics for Facade v
4 min read
Difference Between Architectural Style, Architectural Patterns and Design Patterns
Many software professionals think that architectural styles and patterns are the same. Sadly, some of the software developers don’t understand the difference between architectural patterns and design patterns. In this article, we're going to summarize the differences between them. According to MSDN, architectural styles and patterns are the same th
7 min read
Connectivity and Composition Patterns | Design Patterns for Cloud Native Applications
In cloud-native applications, the architectural design becomes a critical aspect, defining the success of the entire solution. Connectivity and composition patterns are fundamental design principles that dictate how different components within a cloud-native application communicate and collaborate. Let's delve deeper into the significance of these
9 min read
Decorator Pattern | Set 3 (Coding the Design)
We have discussed Pizza design problem and different naive approaches to solve it in set 1. We have also introduced Decorator pattern in Set 2. In this article, design and implementation of decorator pattern for Pizza problem is discussed. It is highly recommended that you try it yourself first. The new class diagram (Click on the picture to see it
5 min read
Decorator Design Pattern
The Decorator Design Pattern is a structural design pattern that allows behavior to be added to individual objects dynamically, without affecting the behavior of other objects from the same class. It involves creating a set of decorator classes that are used to wrap concrete components. Important Topics for Decorator Design Pattern What is a Decora
9 min read
Decorator Design Pattern in JavaScript
The Decorator Design Pattern in JavaScript is a structural design pattern that allows behavior to be added to individual objects dynamically, without affecting the behavior of other objects from the same class. It involves creating a set of decorator classes that are used to wrap concrete components. Important Topics for the Decorator Design Patter
10 min read
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
State Method Design Pattern | C++ Design Patterns
In software design, managing the behavior of an object according to its internal state is a common issue. The state pattern addresses this issue by allowing an object to alter its behavior every time its internal state changes. This pattern encapsulates each state in a separate class, which makes it easier to add new states and modify existing stat
7 min read
Template Method Design Pattern | C++ Design Patterns
Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs. Important Topics for Template
7 min read