Tuesday, June 14, 2011

What is Facade Pattern?

  • Facade pattern is a structural design pattern.
  • Makes an existing complex software library easier to use by providing a simpler interface for common tasks.
  • Allows the applications/ clients using the library de-coupled from inner workings of a complex library.

Demonstrate a simple Facade Pattern in C++

#include <iostream>
using namespace std;

// Transfer library
class Usb {
public:
    bool isAvailable()
    {
        return false;
    }

    void connect()
    {
        cout << "Connecting via USB" << endl;
    }

    void send(string file)
    {
        cout << file << " sent." << endl;
    }
};

class Bluetooth {
public:
    bool isAvailable()
    {
        return true;
    }

    void connect()
    {
        cout << "Connecting via BT" << endl;
    }

    void authenticate()
    {
        cout << "Authenticating BT" << endl;
    }

    void send(string file)
    {
        cout << file << " sent." << endl;
    }
};

// The Facade
class FileTransfer {
public:
    void sendFile(string fileName)
    {
        Usb* u = new Usb();
        Bluetooth* b = new Bluetooth();
        if ( u->isAvailable() )
        {
            u->connect();
            u->send(fileName);
        }
        else if ( b->isAvailable() )
        {
            b->connect();
            b->authenticate();
            b->send(fileName);
        }
        else
        {
            cout << "Not sent" << endl;
        }
        delete b;
        delete u;
    }
};

// Test Program
int main()
{
    FileTransfer* ft = new FileTransfer();
    ft->sendFile("mypicture");
    delete ft;
}
OUTPUT:-
Connecting via BT
Authenticating BT
mypicture sent.

1 comment :

  1. You provide a nice blogs on C++ topics and patterns. Very clear, straight forward, short and direct to the point. Thanks.

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top