Structural Patterns in Practice

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 interfaces and classes:

TypeScript
interface IWinButton {
    render(): void;
}

class WinButton implements IWinButton {
    render(): void {
        console.log("Rendering a button in a Windows style.");
    }
}

class MacButton {
    display(): void {
        console.log("Rendering a button in a Mac style.");
    }
}

Our WinButton class implements the IWinButton interface with a render method, while the MacButton class has a display method. To adapt MacButton to work within systems expecting an IWinButton interface, we apply the Adapter Pattern by creating an adapter class:

TypeScript
class ButtonAdapter implements IWinButton {
    private button: MacButton;

    constructor(button: MacButton) {
        this.button = button;
    }

    render(): void {
        this.button.display();
    }
}

Here, ButtonAdapter adapts MacButton to the IWinButton 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:

TypeScript
const macButton: MacButton = new MacButton();
const winButton: IWinButton = new ButtonAdapter(macButton);
winButton.render(); // Output: Rendering a button in a Mac style.

This code instantiates a MacButton and adapts it using ButtonAdapter, enabling it to render with a Windows-style interface.

Composite Pattern Recap

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal