mardi 25 août 2015

Can I use something other than dynamic_cast in this design?

In our system, we have

  • multiple deviceTypes
  • each deviceType can have a different configuration type
  • each deviceType will be a library of its own

I'm in a situation where I am forced to use dynamic_cast. I'm wondering if there is a better way to design this.

what I have is:

// in common code
class Config {public: virtual ~Config(){} }; 

    class Device {
     protected:
        Config* devConfig;
    protected:
        virtual void createDevConfig() = 0;
    public:
        virtual void display() = 0;
    };

    // Device specific Code
    class A0Device : public Device {
    protected:
        virtual void createDevConfig() { this->devConfig = new A0Config(); }
    public:
        A0Device() { this->createDevConfig(); }

        virtual void display(){
        A0Config* config = dynamic_cast<A0Config*>(this->devConfig);

        if(!config) std::cout << "Null object\n";

        std::cout << config->getpConfig()->getA();
        }
    };

    class BlockAConfig {}; // in /common

    class A0PConfig {
    int a;
    public:
    A0PConfig():a(50){}

    int getA() { return a; }
    };
    class A0TConfig {};

    class A0Config : public Config {
    protected:
        BlockAConfig* blockAConfig;
        A0PConfig* pConfig;
        A0TConfig* tConfig; 

    public:
        A0Config(){
        this->blockAConfig = new BlockAConfig();
        this->pConfig = new A0PConfig();
        this->tConfig = new A0TConfig();
        }

        inline A0PConfig* getpConfig() { return this->pConfig; }
    };

    int main() {
        Device* dev = new A0Device();
        dev->display();
        return 0;
    }

Essentially A0Device has its own config type: A0Config, which is composed of other members. A0Device has devConfig defined as Config* in base class. In A0Device::display() - I need to access the devConfig object (as A0Config type). The virtual createDevConfig() ensures the config object will always be of type A0Config in A0Device => Is it safe to use dynamic_cast here ? Is there a better way of designing this ?

Aucun commentaire:

Enregistrer un commentaire