Dynamically create objects by type name

Source: Internet
Author: User

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 ...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.