mardi 3 mars 2020

Design Patterns: Command + Singleton in C++

Requirements: 1. The server provides clients with the necessary command services: Register, Modify, and Delete commands. 2. The clients get their specific commands by sending command names to the server. 3. The clients execute the fetched command services under the same interface. 4. The server has a single global point of access for clients to get access to. 5. The server achieves a high throughput in the situation where multiple clients get access at the same time by providing clients with pre-created command instances.

Solutions: 1. Meeting the requirements 1 and 2. -> Use the Command Pattern. 2. Meeting the requirement 3. -> Each command is implemented and encapsulated under the same interface. 3. Meeting the requirement 4. -> Use the Singleton Pattern. The name is Command Provider. 4. Meeting the requirement 5. -> The singleton of Command Provider has a cache of pre-created command instances.

Source Code:

    #include <iostream>

    using namespace std;

    enum CommandName {Register, Modify, Delete};

    class Command {
        public:
            Command(){};
            virtual void execute(string value) {};
    };

    class RegisterCommand:public Command {
        public:
            RegisterCommand(){};
            void execute(string value) {
                cout << "Registered " + value << endl;
            };
    };

    class ModifyCommand:public Command {
        public:
            ModifyCommand(){};
            void execute(string value) {
                cout << "Modified " + value << endl;
            };
    };

    class DeleteCommand:public Command {
        public:
            DeleteCommand(){};
            void execute(string value) {
                cout << "Deleted " + value << endl;
            };
    };

    class CommandProvider {
        static Command* cache[];
        public:
            static Command* getCommand(CommandName commandName) {
                return cache[commandName];
            };
    };

    Command* CommandProvider::cache[3] = {new RegisterCommand(), new ModifyCommand(), new DeleteCommand()};

    class Client1 {
        public:
            void doWork() {
                            CommandName commandName = Register;
                            Command* command = CommandProvider::getCommand(commandName);
                            command->execute("Mike");
            };
    };

    class Client2 {
        public:
            void doWork() {
                            CommandName commandName = Delete;
                            Command* command = CommandProvider::getCommand(commandName);
                            command->execute("Mary");
            };
    };

    int main() {
        Client1* client1 = new Client1();
        client1->doWork();

        Client2* client2 = new Client2();
        client2->doWork();

        return 0;
    } 

Aucun commentaire:

Enregistrer un commentaire