1 Introduction
One of my actual projects, because I want to control various types of equipment through a consistent interface, and can be easily expanded at any time, so as to support more models in the future. Therefore, you must specify the model of the device at run time.
In order to enable the application to control various types of devices transparently, a simple inheritance system is established, a protocol class (Protocol Class) is designed as the control interface of the device, and a specific class is designed for each type of device, derived from the Protocol class and implements the abstract public interface.
Therefore, I need a means to create a device class instance dynamically at runtime according to the device's model. Otherwise, if the Hard code device is configured at compile time, it will lose practicality and flexibility.
The end result is the need for such a technology to achieve
Motor* motor=ClassByName("IM9001");
Similar functionality.
2 Design and implementation
The code snippet for the existing key class is as follows:
class IntelligentMotor
{
public:
IntelligentMotor(const std::string& port_name);
virtual bool Start()=0;
virtual bool Stop()=0;
virtual ~IntelligentMotor();
};
class IM9001 : public IntelligentMotor
{
public:
IM9001(const std::string& port_name);
virtual bool Start();
virtual bool Stop();
virtual ~IM9001();
private:
// ...
};
class IM9002 : public IntelligentMotor
{
public:
IM9002(const std::string& port_name);
virtual bool Start();
virtual bool Stop();
virtual ~IM9002();
private:
// ...
};
// more model ...