Adapter

Wraps an interface/library in your own specified format to adapt to your needs. This way you can abstract your specific needs from the interface as to not clutter the rest of the application with how the provided library actually works. There are two ways to do this:

Class adapter: adapter inherits from the adaptee type

Object adapter: adapter contains an object of the adaptee type

Use when:

Example C++ Code


// the client class: shape which expects the target to define a rectangle of its area (bounding box)
class Shape
{
public:
    virtual void BoundingBox(Point &bottomLeft, Point &bottomRight) = 0;
};

// the adaptee: the class that needs to be adapted - it provides a size (get extent) and coordinates (get origin)
// but not a bounding box
class TextView
{
public:
    void GetOrigin(Coord &x, Coord &y) const;
    void GetExtent(Coord &width, Coord &height) const;
};

// the adapter: a class adapter inheriting from TextView
class TextShape: public Shape, private TextView
{
public:
    void BoundingBox(Point &bottomLeft, Point &bottomRight)
    {
        Coord bottom, left, width, height;
        
        // call the necessary adaptee functions
        GetOrigin(bottom, left);
        GetExtent(with, height);

        // translate them into the required form
        bottomLeft = Point(bottom, left);
        topRight = Point(bottom + height, left + width);
    }
};