Why run-time Polymorphism needed ?

Why run-time Polymorphism needed ?

There are many good articles on working and use of run-time polymorphism. But why this concept needed in OOPs in first place? What are the situations a developer get into to use the dynamic-binding practically are not much explained in internet, so this attempt.

Consider multiple team are going to create multiple widgets like TextBox, Button etc, so Architect share the template class called Widget to all the teams like Button Team, TextBox team, Render Team. All teams will work independently and parallelly.

class Widget {
public:
    virtual void draw() = 0;
};        

Now, Button Widget team will inherit and start implementation as

class Button : public Widget {
public:
    void draw() override {
        std::cout << "Drawing Button" << std::endl;
    }
};        

Similarly, TextBox team will inherit Widget and start implementation multiple methods also the draw() method which is mandatory as it is pure virtual.

class TextField : public Widget {
public:
    void draw() override {
        std::cout << "Drawing TextField" << std::endl;
    }
};        

And, Rendering team will provide a API as below, where it can accept Widget class pointer as argument. And render() is expected to draw any widget(Textbox, Button or any CustomWidget) that is sent as argument in the screen.

void render(Widget* widget) {
    widget->draw();
}        

Integrator can integrate the newly developed widgets and test it using render API as below,

int main() {
    Button button;
    TextField textField;

    render(&button);       
    render(&textField);

    return 0;
}        

Output

Drawing Button
Drawing TextField        

So it benefits on,

Consistency: Teams can work independently on their modules, knowing they must adhere to a common interface.

Abstraction: Users of a class(here render()) only need to know about the base class interface, not the specifics of each derived class.

Extensibility: You can introduce new derived classes without changing the existing code that uses the base class.

Another example:

// This is Abstract class given to all team
class Logger {
public:
    virtual void log(const std::string &message) = 0;
};

// Console logger team
class ConsoleLogger : public Logger {
public:
    void log(const std::string &message) override {
        std::cout << "Console Log: " << message << std::endl;
    }
};

// File logger team
class FileLogger : public Logger {
public:
    void log(const std::string &message) override {
        // Code to log message to a file
        std::cout << "File Log: " << message << std::endl;
    }
};

// Another team offers performLogging() API to the developer.
void performLogging(Logger* logger, const std::string &message) {
    logger->log(message);
}        

Now, Developer has to decide where to log the message and call only

performLogging(new FileLogger(), "Voila");        

要查看或添加评论,请登录

M Vijaynath的更多文章

社区洞察

其他会员也浏览了