Tuesday

Software Design Patterns: Facade pattern using C++

Under Structural Patterns

Why?
Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use

Code:
#include <string>

#include <iostream>

using namespace std;


class Alarm

{

public:

    void alarmOn()

    {

        cout << "Alarm is on"<<endl;

    }


    void alarmOff()

    {

        cout << "Alarm is off"<<endl;

    }

};


class Ac

{

public:

    void acOn()

    {

        cout << "Ac is on"<<endl;

    }


    void acOff()

    {

        cout << "Ac is off"<<endl;

    }

};


class Tv

{

public:

    void tvOn()

    {

        cout << "Tv is on"<<endl;

    }


    void tvOff()

    {

        cout << "TV is off"<<endl;

    }

};


class FacadeHouse

{

    Alarm alarm;

    Ac ac;

    Tv tv;


public:

    FacadeHouse() {}


    void goToWork()

    {

        alarm.alarmOn();

        ac.acOff();

        tv.tvOff();

        cout << endl;

    }


    void comeHome()

    {

        alarm.alarmOff();

        ac.acOn();

        tv.tvOn();

        cout << endl;

    }

};


int main()

{

    FacadeHouse facadeHouse;


    //rather than calling 100 different on and off functions thanks to Facade

    facadeHouse.goToWork();

    facadeHouse.comeHome();

}


Sample run:
Alarm is on
Ac is off
TV is off

Alarm is off
Ac is on
Tv is on

No comments:

Measure execution time with Julia, example using sorting algorithms

# random integers between 1 and 100 inclusive, generate thousands of them x = rand ( 1 : 100 , 100000 ) @time sort (x; alg=InsertionSort, r...