Saturday, May 3, 2014

Command Design Pattern

// Implementing Command Design pattern. This is behavioral pattern which allows
// to encapsulate request as an object.

#include <iostream>

using namespace std;

class FileCommand{
        public:
                virtual void execute(){}
};

class FileOpen : public FileCommand{
        public:
                void execute()
                {
                        cout<<"File Opened.."<<endl;
                }
};

class FileClose : public FileCommand{
        public:
                void execute()
                {
                        cout<<"File Closed.."<<endl;
                }

};
//Invoker Class
class FileCommandInvoker{
        FileCommand* array[2];
        public:
                FileCommandInvoker()
                {
                        array[0] = new FileOpen();
                        array[1] = new FileClose();

                }
                FileCommand* getCommand(int command)
                {
                        FileCommand *fc = 0;
                        if(command == 1)
                                fc = array[0];
                        else if(command == 2)
                                fc = array[1];

                        return fc;
                }
};

//Client Code
int main()
{
        int command;
        cout<<"1. File Open  "<<endl;
        cout<<"2. File Close "<<endl;
        cout<<"Enter 1-2 : "<<endl;
        cin>>command;
        FileCommandInvoker *fci = new FileCommandInvoker();
        FileCommand *fc = fci->getCommand(command);
        fc->execute();
        return 0;
}

No comments:

Post a Comment