Adapter Pattern: Pluggable Adapters, Implementation, and Bridge Pattern

This page continues the Adapter pattern discussion with pluggable adapter variants and full C++ implementation examples, then introduces the Bridge pattern — a structural pattern that decouples an abstraction from its implementation so both can vary independently. The page also begins introducing the Composite pattern.

Key Concepts

Commands and Syntax

Class Adapter (multiple inheritance):


class TextShape : public Shape, private TextView {
    // public Shape = inherit interface
    // private TextView = inherit implementation
    void BoundingBox(Point& bl, Point& tr) const {
        Coord bottom, left, width, height;
        GetOrigin(bottom, left);      // calls TextView directly
        GetExtent(width, height);
        bottomLeft = Point(bottom, left);
        topRight = Point(bottom + height, left + width);
    }
    bool IsEmpty() const { return TextView::IsEmpty(); }  // direct forwarding
};

Object Adapter (composition):


class TextShape : public Shape {
    TextView* _text;  // holds reference to adaptee
public:
    TextShape(TextView* t) { _text = t; }
    void BoundingBox(Point& bl, Point& tr) const {
        _text->GetOrigin(bottom, left);   // delegates to adaptee
        _text->GetExtent(width, height);
    }
};

Parameterized Adapter (Smalltalk blocks):


directoryDisplay :=
    (TreeDisplay on: treeRoot)
        getChildrenBlock: [:node | node getSubdirectories]
        createGraphicNodeBlock: [:node | node createGraphicNode].

Bridge — Abstraction forwards to Implementor:


class Window {
    WindowImp* _imp;
    WindowImp* GetWindowImp();  // lazy-loads from abstract factory
    void DrawRect(const Point& p1, const Point& p2) {
        WindowImp* imp = GetWindowImp();
        imp->DeviceRect(p1.X(), p1.Y(), p2.X(), p2.Y());
    }
};

Bridge — Implementor obtained via Abstract Factory:


WindowImp* Window::GetWindowImp() {
    if (_imp == 0) {
        _imp = WindowSystemFactory::Instance()->MakeWindowImp();
    }
    return _imp;
}

Relationships

Exam-Relevant Points