Structural patterns

The seven structural patterns of the GoF catalogue: Adapter, Bridge, Composite, Decorator, Facade, Flyweight and Proxy. Intent, participants, a code example and patterns that look alike.

  • 23 cards
  • 4 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Understand

A few cards from the deck

  • Adapter: what is it?

    Show the answer

    Structural pattern that converts the interface of an existing class into the one the client expects.

    It makes classes with incompatible interfaces work together without changing either, for example to plug an old API into our interface.

  • What does price() return for this coffee?

    ```java
    interface Drink { double price(); }
    class Coffee implements Drink {
    public double price() { return 2.0; }
    }
    class Sugar implements Drink {
    private final Drink d;
    Sugar(Drink d) { this.d = d; }
    public double price() { return d.price() + 0.2; }
    }
    class Milk implements Drink {
    private final Drink d;
    Milk(Drink d) { this.d = d; }
    public double price() { return d.price() + 0.5; }
    }
    // new Milk(new Sugar(new Coffee())).price()
    `

    • 2.7
    • 2.5
    • 0.7
    • 2.2
    Show the answer

    2.7

    The call goes from the outermost wrapper inward, then the prices come back up: 2.0 (coffee) + 0.2 (sugar) + 0.5 (milk) = 2.7. Each decorator adds its share to the price of what it wraps.

  • A Decorator and the object it wraps implement the …, which lets several decorators be stacked.

    Show the answer

    A Decorator and the object it wraps implement the same interface, which lets several decorators be stacked.

    The client cannot tell whether it holds the raw object or a decorated one. It is also what sets Decorator apart from Adapter, which changes the interface.

  • Bridge: what is it?

    Show the answer

    Structural pattern that separates an abstraction from its implementation so the two can vary independently.

    It avoids a class explosion: 3 remotes and 4 devices make 3 + 4 classes with a bridge, instead of 12 through inheritance.

  • To plug a payment library into our Payment interface, why write an Adapter rather than change the library's class?

    • An existing class can never implement an extra interface
    • The Adapter makes calls faster than direct calls
    • The Adapter adds behaviour the library does not have
    • The library's code is not ours: we wrap it without touching it
    Show the answer

    The library's code is not ours: we wrap it without touching it

    The adapted class comes from elsewhere and will change with its versions: the Adapter implements Payment and translates each call to the adapted object it holds. It only translates; adding behaviour is the Decorator's job.