1

I have a quick question about my individual implementation of Facade pattern, just to be sure that I've understood it right: I have class called Car, which is figuring as a facade for Engine and Lights. Also, I have a Driver class which could call methods for different kinds of cars. Does my code meet the requirements of proper implementation of facade pattern?

#include <iostream>
#include <memory>

class Engine
{
public:
    void turnOn()
    {
        std::cout << "Engine turned on. \n";
    }
};

class Lights
{
public:
    void turnOn()
    {
        std::cout << "Lights turned on. \n";
    }
};

class Car // Facade for Engine and Lights
{
private:
    std::shared_ptr<Engine> m_engine;
    std::shared_ptr<Lights> m_lights;
public:
    Car(std::shared_ptr<Engine> engine, std::shared_ptr<Lights> lights) : m_engine{ engine }, m_lights{ lights } {}
    void turnCarOn()
    {
        std::cout << "Turning car on... \n";
        m_engine->turnOn();
        m_lights->turnOn();
    }
};

class Driver // Facade for Car
{
private:
    std::shared_ptr<Car> m_car;
public:
    Driver(std::shared_ptr<Car> car) : m_car{ car } {}
    void turnCarOn()
    {
        std::cout << "Driver presses some buttons... \n";
        m_car->turnCarOn();
    }
};

int main()
{
    std::shared_ptr<Engine> engine = std::make_shared<Engine>();
    std::shared_ptr<Lights> lights = std::make_shared<Lights>();
    std::shared_ptr<Car> car = std::make_shared<Car>(engine, lights);
    std::shared_ptr<Driver> driver = std::make_shared<Driver>(car);
    driver->turnCarOn();
}
Christophe
  • 68,716
  • 7
  • 72
  • 138
Thorvas
  • 45
  • 10

1 Answers1

0

Yes, your implementation satisfies the requirement.

Having the ability to have a Facade for different kind of cars, requires the Facade not only to blindly forward the calls to the components that it hides, but also configure the set of components of a specific Car.

You allow this with the help of your shared pointers m_engine and m_lights

For a more precise argumentation with authoritative references, you may look at this answer to another SO question (which was for java).

Christophe
  • 68,716
  • 7
  • 72
  • 138