Code

Implementing the Decorator Pattern in Java

Implementing the Decorator Pattern in Java

Free Python Course ➞ Mini-course for beginners and experienced coders. 4 cool projects for your portfolio, live chat with the speaker. Click and find out what you can learn in the course.

Learn more

In this article, we continue our exploration of design patterns. In the first part, we delved into working with data from NASA's Mars rover. Today, we'll create a unique universe and populate it with creatures with unique superpowers. This process requires a careful approach to design to ensure the harmonious interaction of all elements. By using various design patterns, we can effectively organize the structure of our universe and its inhabitants, which will allow us to create a fascinating and functional world.

  • Problem Statement
  • Solution 1: Create many individual classes
  • Solution 2: Move all the logic to the base class
  • Solution 3: Apply the Decorator pattern
  • To summarize

Problem Statement

Creating a program to compare two superheroes and determine which of them has a better chance of surviving a battle is an interesting problem. This program must analyze various characteristics of superheroes, such as strength, speed, intelligence, experience, and special abilities. It is important to consider not only physical parameters, but also strategic skills, as well as weaknesses of each hero.

To implement this program, you can use algorithms that will evaluate each of the characteristics and assign them specific weights. This will allow for more accurate comparison results. It is also worth adding the ability to take into account the context of the battle, such as the environment and conditions in which the battle takes place.

Thus, the program will become a powerful tool for analyzing and predicting the results of battles between superheroes, which will be of interest to both comic book fans and game developers.

In our unique world, there are two types of heroes: green and red. Each of these heroes is capable of possessing one or more superpowers, such as superstrength, superagility, and superintelligence. These abilities allow them to perform extraordinary feats and protect the world from threats. Green heroes tend to represent symbols of hope and harmony, while red heroes embody strength and determination. Their interaction creates a dynamic that attracts attention and inspires.

The fate of a hero is directly linked to their chance of survival. Red heroes initially have a slightly higher chance, but each activated superpower significantly increases the likelihood of a successful outcome. The more unique abilities a hero uses, the more opportunities they have to survive in critical situations. Thus, the strategic use of superpowers becomes a key element in increasing the hero's chances of survival.

  • super strength - by 4;
  • super agility - by 3;
  • super intelligence - by 7.

In a battle between two superheroes, the one with the higher final chance wins. This principle is applicable in various scenarios where the outcome depends on probabilities. In such battles, the key factor is not only the strength of the heroes, but also their tactical decisions, ability to use their abilities and analyze the situation. The higher the final chance, the greater the likelihood of success in the confrontation.

In this problem, we focus exclusively on the hero's characteristics and their survival abilities. The superhero's primary interface will be represented by the following elements: a description of their appearance, unique skills, level of physical fitness, and adaptation characteristics. These aspects will help create a complete picture of the hero and their potential in challenging situations.

The Green Superhero class is a unique opportunity to learn and develop abilities that make them outstanding environmental defenders. This class emphasizes the importance of nature conservation and sustainable development. The Green Superhero uses their powers not only to fight crime but also to preserve ecosystems and raise awareness of environmental issues. Unique skills such as manipulating natural elements, creating eco-friendly technologies, and the ability to inspire others to take action to protect the planet make them a true symbol of the fight for environmental justice. Join the Green Superhero class and become part of the movement for a clean and safe planet.

For a more stable and vibrant red color, choose varieties with high vitality. These plants not only attract attention with their rich hue, but also retain their beauty for a long time, even in adverse conditions. Make sure the variety you choose is suitable for your region and climate. Proper care, including regular watering and fertilizing, will help ensure your plant is healthy and produces rich color throughout the season.

Create Many Individual Classes

You can follow the Marvel example and assign each possible hero variant a unique name, creating a separate class. For example, a green superhero with powerful strength and outstanding intelligence could be called the Hulk, while a red hero with high intelligence and outstanding agility would become Spider-Man. This allows you to create a variety of characters and make them recognizable, which is important for generating interest and audience engagement.

A total of 16 classes will be created, eight of which are combinations of three superpowers for red characters, and the remaining eight are for green characters.

The Hulk class represents a powerful and unique embodiment of strength and destruction. Known for his incredible physical potential, this character has become a symbol of unbridled rage and protection. Created based on a scientific experiment, the Hulk demonstrates a transformation from a human into a gigantic green creature when faced with strong emotions, such as anger. His abilities include not only colossal strength but also a high rate of recovery, making him virtually invulnerable. In the comic book world, the Hulk has become an icon, reflecting the struggle with inner demons and the search for one's place in society. This character continues to inspire and amaze, remaining relevant in various media formats, from comics to film.

The number of classes is already large, and with each new superpower added, their number will double for each superhero type. This can complicate the game balancing and the perception of different classes by players.

If we decide to add not a superpower, but a new type, for example, yellow superheroes, the number of classes will increase by 2n, where n is the number of superpower variants. Thus, expanding the classification of superheroes can significantly increase the diversity of characters and their unique characteristics.

To calculate the necessary information, several key factors should be taken into account. First, determine the parameters that need to be measured. Then, collect all the data that can affect the result. Use appropriate formulas or calculation methods to obtain accurate values. It is also important to check the results for accuracy and compliance with expectations. Regular analysis and revision of calculations will help improve the understanding of the process and improve its effectiveness.

Each hero type, be it red or green, has two main states: the presence of superpowers or their absence.

Each of the presented variants has either super agility or its absence. Thus, for each of the two options, there are two more sub-options, for a total of four possible combinations.

Each of the four superintelligence options under consideration can have these characteristics: it can be either present or absent.

The number 4 times 2 equals 8. This expression is a simple mathematical operation that shows that when you multiply four by two, you get eight. Multiplication is one of the basic arithmetic operations, and understanding its principles is important for solving more complex problems. In this case, the 8 options can represent different combinations or results that can be obtained when using these numbers in different contexts.

Each superpower doubles the number of possible superhero options for each color. This means that with n superpowers, the total number of unique superheroes is 2 to the power n, emphasizing the diversity and potential of characters in this category.

When creating a new class, you must manually define a description and develop a method for calculating the chances of survival. It's easy to get lost in such a zoo, and any changes can lead to significant difficulties. Effective management of classes and their parameters is a key aspect of successful work in this system.

Move all logic to the base class

Let's reduce the number of classes, keeping only classes for the red and green superheroes. Instead, we'll create a base class that includes methods for describing the hero and calculating his chances of survival. This will optimize the code structure and simplify further development, while providing flexibility and the ability to extend functionality.

The base class will look like this:

Small changes need to be made to the RedSuperHero and GreenSuperHero classes so that they inherit from the base class. For example, for a red superhero class, it would look like this:

To create a red superhero with super intelligence and super agility, you need to create an instance of the RedSuperHero class and set the corresponding properties to true. This will give your character unique abilities that will set them apart from other heroes. Make sure all the necessary parameters are set correctly to maximize the potential of your superhero.

There are fewer classes, and all the logic is now concentrated in one place. This simplifies code management and improves readability. The streamlined structure makes it easier to make changes and improvements, which ultimately contributes to more efficient development and maintenance of the project. Concentrating logic in one place also reduces the likelihood of errors and improves code testability.

  • When adding a new ability, you will have to add properties to the base class and change the implementation logic of the methods - now the methods will become longer and more complex;
  • If we want to slightly complicate our world and decide that not all hero types can have all the superpowers, the derived classes will still contain all the methods of the base class - there is no other way with inheritance;
  • Doubling or tripling any superpower - for example, giving a hero double superpowers - in such a class structure also will not work: you will need more classes or new properties.

To ensure diversity and eliminate the shortcomings of inheritance, it is recommended to use the Decorator design pattern. This pattern allows you to dynamically add new functionality to objects without changing their structure. Decorator provides flexibility and extensibility, allowing you to create complex objects from simple ones by combining different decorators. This is especially useful in cases where you need to avoid complex class hierarchies and simplify change management within the system. Using the Decorator pattern promotes better adherence to SOLID principles and improves code readability.

Using the Decorator Pattern

The Gang of Four's design pattern, known as the Decorator, allows you to dynamically add new behavior to an object. This approach is an alternative to creating multiple derived classes that implement a given behavior. Using decorators provides greater flexibility and simplifies code, allowing developers to extend the functionality of objects without changing their original class. This approach promotes the single responsibility principle and improves code readability and maintainability.

The Decorator pattern has a descriptive name: it takes a given object and adds additional functionality or properties to it. Regardless of the decorations used, the end result should remain an object of the same type, but with enhanced capabilities. For example, after applying a decorator to a superhero, they should remain a superhero with new superpowers, and not transform into a completely different creature, such as a Transformer or a dinosaur.

Therefore, it is important to understand that effective audience engagement requires a careful approach. To achieve success, it is necessary to consider the interests and needs of the target group. This allows you to create content that will not only attract attention but also retain user interest. It is also important to optimize the text for search engines, including keywords and phrases that will help improve the visibility of the site. High-quality content helps build trust in your brand and increases the likelihood of conversion. Don't forget to regularly update the information, which will help keep your site relevant and attractive.

  • The decorator class must be the same type as the class being decorated - implement the same interface or inherit the same base class.
  • The decorator implements the behavior of the original class; It does not change it, but adds its own behavior before or after calling the base class.
  • This is achieved due to the fact that the decorator contains an object of the base class and calls its methods where the behavior needs to be supplemented.

Here is a representation on a class diagram:

Class diagram. Infographics: Maya Malgina for Skillbox Media

There are two main types of classes: "regular" classes, known as ConcreteComponents, and decorator classes, which add new capabilities to them. Decorator classes are also called wrapper classes, as they contain an object, providing additional functionality. This allows for flexible extension of the behavior of regular classes without changing their internal structure.

Imagine multi-layered clothing, where each layer performs its own important function. The first layer effectively wicks moisture away from the body, keeping you comfortable and dry. The second layer retains heat, creating a cozy atmosphere even in cold weather. The third layer protects from wind and rain, providing a reliable barrier. Together, these layers form a protective "cocoon," allowing a person to successfully cope with changing weather conditions. This approach to choosing clothing allows you to stay active and comfortable in any climate.

Let's return to the topic of superheroes and consider the application of the Decorator pattern. We'll begin by creating a base decorator class. This class will become the basis for adding new functionality to superhero objects without changing their source code. The Decorator pattern allows you to dynamically extend the behavior of objects, which is especially useful in situations where you need to add new characteristics or abilities to a superhero. Now we can move on to implementing the base decorator, which will allow us to flexibly modify objects while preserving their original properties.

This class is abstract, which makes it impossible to create instances of it. This is not necessary, since its main function is to store data about the superhero. We use class methods to obtain information about the hero's characteristics and the probability of their survival. This approach allows you to organize your code structure effectively, minimizing redundancy and ensuring ease of working with data.

If you are not yet familiar with abstract classes, we recommend checking out this article. Here you will find a full explanation of the concept of abstract classes, their features, and applications in programming. Understanding this topic will help you improve your development skills and create more efficient and structured programs.

Let's create a unique decorator that will give your function special power. This decorator will allow you to easily extend functionality without changing the source code. It will add additional features, such as logging, access control, or result caching. When implemented correctly, a decorator will not only improve the code but also make it more readable and maintainable. Now let's look at how to create such a decorator and apply it to our function to unlock its potential.

Wrapper classes for super-dexterity and super-intelligence are created using a similar principle. These classes allow you to effectively manage functionality and provide flexibility in using various characteristics. Proper implementation of wrapper classes helps optimize code and improve its readability, which is especially important for developers looking to improve the performance of their applications. Let's explore the power of decorators by staging a real-life battle between superheroes. In this context, decorators will serve as a tool that adds new functionality and enhances the abilities of our heroes. We'll see how they can modify behavior, enhance skills, and adapt to different conditions. This demonstration will allow us to clearly appreciate how decorators can transform functionality, making it more flexible and efficient. The superhero battle will be an excellent example of decorators in programming, demonstrating their power and versatility in creating complex and feature-rich systems.

The chances of winning are almost equal, but in the end the green superhero, who possesses both superintelligence and outstanding agility, will win.

Console output after running the program. Screenshot: Ekaterina Stepanova for Skillbox Media

Each decorator, when calling a method, for example, to calculate the chance of survival, calls the method of the object of the same name, which was saved in the constructor. After receiving the value from this method, the decorator adds its own number to the result, based on a specific superpower. Thus, decorators allow you to expand the functionality of objects, adding new capabilities and improving their characteristics.

It is important to consider that the object saved in the constructor can also be decorated. In this case, our method will not be able to immediately return the value, but will need to delve deeper into the structure of the object. It must access the internal object, which is already inside the second decorator. This complicates the processing, since additional levels of decoration must be taken into account.

The process will continue until we get a "clean" An object that accurately determines its chances of survival. This object will pass the value to the first decorator that calls it. The decorator will increment the value according to its own implementation and pass the result back to the caller. This process will repeat until we return to the starting point.

Recursion is an important concept in programming, and if you're familiar with it, you've already noticed its use in this algorithm. If you're not familiar with recursion, we recommend familiarizing yourself with its basics to better understand the mechanics of algorithms that use this approach. Recursion allows you to solve complex problems by breaking them down into simpler subproblems, making the code more concise and understandable.

The image below shows an example of calculating the survival probability for the first superhero from the previously mentioned list. This analysis allows you to evaluate the character's chances in various situations, which can be useful for creating scenarios and developing the plot.

Infographics: Maya Malgina for Skillbox Media

The "Decorator" template allows you to add new superpowers to classes without having to change them. This approach allows for combining different abilities and creating characters with multiple skills. For example, you could design a superhero with double super agility, significantly expanding their capabilities and making them more unique. This pattern makes character creation and modification more flexible and efficient.

If your program's logic depends on specific classes, using the Decorator pattern may be ineffective. For example, if green superheroes should become more agile than red superheroes as a result of applying super agility, standard inheritance is preferable. This will provide a simpler and more understandable code architecture while preserving the necessary functionality.

Decorators work with SuperHero objects, accepting and returning them, without taking into account the specific characteristics of superheroes. As a result, after applying the decorator, information about the superhero type (in this case, their color) is lost. This limitation should be taken into account when designing a decorator system to preserve important properties of objects.

To summarize

The Decorator design pattern is an effective tool for dynamically adding new functionality to objects. It is an excellent alternative to inheritance, especially in situations where there is no need to consider the specific types of decorated objects in the program logic. Using this pattern improves the flexibility and extensibility of code, providing the ability to change the behavior of objects without having to modify them. Thus, the Decorator pattern contributes to a cleaner and more maintainable architecture of software solutions.

In the "Java Developer PRO" course, you will learn various design patterns, algorithms, data structures, and object-oriented programming concepts using the Java language. The course program is aimed at mastering this in-demand programming language and developing high-quality applications for various platforms. Skillbox also provides job placement support to help you successfully launch a career in Java development.