Real-world Application of Structural Patterns in JavaScript
Real-world Application of Structural Patterns
We are progressing in our understanding of Structural Patterns. In this lesson, we’ll see how to apply them in a practical example by creating a GUI library. So far, we’ve explored the Adapter, Composite, and Decorator Patterns independently. Now, we’ll integrate these patterns within a GUI library context to form a cohesive project. Note that these patterns are abstract and can be applied in various other scenarios beyond GUI libraries.
Adapter Pattern Recap
Let's quickly revisit the Adapter Pattern. This pattern allows two incompatible interfaces to work together. We accomplish this by creating an adapter class that converts one interface to another. In the context of our GUI library, consider the following classes:
Our WinButton class has a render method, while the MacButton class has a display method. To adapt MacButton to work within systems expecting a WinButton interface, we apply the Adapter Pattern by creating an adapter class:
Here, ButtonAdapter adapts MacButton to the WinButton interface, allowing it to be used interchangeably. This allows the MacButton instance to be treated like a WinButton.
Intermediate Adapter Steps
First, let's create the MacButton and wrap it with the ButtonAdapter:
This code instantiates a MacButton and adapts it using ButtonAdapter, enabling it to render with a Windows style.
Composite Pattern Recap
The Composite Pattern helps us compose objects into tree structures to represent part-whole hierarchies. This allows clients to treat individual objects and compositions of objects uniformly. For our GUI library, we use the Composite Pattern to manage components:
Let's create a Container class that will act as a composite class containing other components:
We also need a Button class that will be a concrete component:
The Container can hold and manage multiple components, such as buttons, efficiently, implementing the Composite Pattern.
