samedi 29 janvier 2022

Runtime factory design patterns

Let's assume I have the following classes:

class Listner
{
    ...
    int first_call = true;
    DataReader * reader;
    ***
    int dataIsAvailable(char * data, int len) {
        if (first_call) {
            if (data[0] == 'R') {
                reader = new RawReader();
            } else if (data[0] == 'E') {
                reader = new SecureReader();
            }
            first_call = false;
        }
        
        reader->read(data, len);
        printf("%s", data);
        
    }
}

class DataReader
{
    long read(...) = 0;
}

class RawReader : public DataReader
{
    long read(char * data, int len) {
        return ::recv(char * data, int len);
    }
}

class SecureReader : public DataReader
{
    long read(char * data, int len) {
        auto ret = ::recv(char * data, int len);
        decrypt(data, len)
        return ret;
    }
}

dataIsAvailable is called when there is new data available.

In this case, I know if the content is encrypted too late and it makes me check every time if this is the first time. Is there a way to avoid it?

Aucun commentaire:

Enregistrer un commentaire