Before you begin: Join our book community on Discord
Give your feedback straight to the author himself and chat to other early readers on our Discord server (find the “architecting-aspnet-core-apps-3e” channel under EARLY ACCESS SUBSCRIPTION).
https://packt.link/EarlyAccess
This chapter explores four design patterns from the well-known Gang of Four (GoF). We use Structural patterns to build and organize complex object hierarchies in a maintainable fashion. They allow us to dynamically add behaviors to existing classes, whether we designed the initial system this way or as an afterthought that emerges out of necessity later in the program’s lifecycle. Structural patterns promote reusability and enhance the overall flexibility of the system.In this chapter, we cover the following topics:
- Implementing the Decorator design pattern
- Implementing the Composite design pattern
- Implementing the Adapter design pattern
- Implementing the Façade design pattern
The first two patterns help us extend a class dynamically and efficiently manage a complex object structure. The last two help us adapt an interface to another or shield a complex system with a simple interface.Let’s dive into unlocking the power of structural patterns!
Implementing the Decorator design pattern
The Decorator Pattern allows us to dynamically add new functionality to an object by wrapping it with one or more decorator objects. This pattern follows the Open-Closed principle, allowing us to add additional behaviors to an object at runtime without modifying its original code. This pattern enables us to separate responsibilities into multiple smaller pieces. It is a simple but powerful pattern. In this section, we explore how to implement this pattern in the traditional way and how to leverage an open-source tool named Scrutor to help us create powerful dependency injection-ready decorators.
Goal
The decorator aims to extend an existing object at runtime without changing its code. Moreover, the decorated object should remain unaware of the decoration process, making this approach an excellent fit for complex or long-lasting systems that necessitate evolution. This pattern fits systems of all sizes.
I often use this pattern to add flexibility and create adaptability to a program for next to no cost. In addition, small classes are easier to test, so the Decorator pattern adds ease of testability into the mix, making it worth mastering.
The Decorator pattern makes it easier to encapsulate responsibilities into multiple classes, instead of packing multiple responsibilities inside a single class. Having multiple classes with a single responsibility makes the system easier to manage.