Composite

Examples

Unix Filesystem

A typical directory structure:

../../../../../_images/73-composite-unixfs.svg

A hypthetical class diagram:

../../../../../_images/73-composite-unixfs-uml.png

Boolean Expressions

../../../../../_images/73-composite-boolexpr-uml.png

Thermometers, And Average Calculation

../../../../../_images/73-composite-thermometer-uml.png

Exercise

Implement the following test:

#include <gtest/gtest.h>

#include <sensor-const.h>
#include <sensor-avg.h>


TEST(composite_suite, basic)
{
    ConstantSensor cs1(3);
    ConstantSensor cs2(4);

    Sensor* s1 = &cs1;     // <--- is-a Sensor
    Sensor* s2 = &cs2;     // <--- is-a Sensor

    AveragingSensor avg;   // <-- uses-many Sensor
    avg.add(s1);
    avg.add(s2);

    Sensor* s = &avg;      // <-- is-a Sensor
    ASSERT_FLOAT_EQ(s->get_temperature(), 3.5);
}

Maybe, as a C++ 11 excursion, lets implement real initialization, and omit the add() method. This way it becomes impossible to add() another member to the composite object at the time it is already being used.

Note

This step is optional!

#include <gtest/gtest.h>

#include <sensor-const.h>
#include <sensor-avg.h>


TEST(composite_suite, initializer_list)
{
    ConstantSensor cs1(3);
    ConstantSensor cs2(4);

    AveragingSensor avg{&cs1, &cs2};

    ASSERT_FLOAT_EQ(avg.get_temperature(), 3.5);
}