我正在尝试实现硬件抽象层(HAL),以使用所有相同的接口访问多个类似的设备。问题是,我应该如何针对一种设备类别与另一种设备类别实施动态转换。以下代码显示了我实际上是如何做到的。但是,我不确定此实现是否足够安全。特别是我不确定使用'shared_ptr'切换实现的正确方法,还是使用工厂模式甚至更多抽象会更好。您对实现这种动态HAL有何建议?
#include <iostream>
#include <string>
#include <memory>
using namespace std;
// Common HAL base class
struct Base {
virtual string Identify() {return string("Baseclass");}
Base() {cout << "Base Constructor" << '\n';}
virtual ~Base() {cout << "Base Destructor" << '\n';}
// Important to make destructor virtual so that destructor of derived classes is invoked, too
};
// HAL Device 1 Implementation
struct Derived1: public Base {
string Identify() override {return string("Derived 1 class");}
Derived1() {cout << "Derived1 Constructor" << '\n';}
~Derived1() {cout << "Derived1 Destructor" << '\n';}
};
// HAL Device 2 Implementation
struct Derived2: public Base {
string Identify() override {return string("Derived 2 class");}
Derived2() {cout << "Derived2 Constructor" << '\n';}
~Derived2() {cout << "Derived2 Destructor" << '\n';}
};
// Switches implementation via setting a pointer to a class instance
struct ImplementationDispatcher {
shared_ptr<Base> Impl = make_shared<Base>();
Base& Implementation() {return *Impl;}
void SetImplementation(shared_ptr<Base> impl) {Impl = impl;}
};
// Top level class which calls HAL device functions
struct Actor {
ImplementationDispatcher HAL;
void Work() {cout << HAL.Implementation().Identify() << '\n';}
void SetActor(shared_ptr<Base> newImpl) {HAL.SetImplementation(newImpl);}
};
int main()
{
Actor actor;
actor.Work();
actor.SetActor(make_shared<Derived1>());
actor.Work();
actor.SetActor(make_shared<Derived2>());
actor.Work();
}
我为所有设备定义了具有通用功能的基类(在本示例中,这只是Identify()
方法)。然后,我为设备实现Derived1
和Derived2
派生类。我想在主代码中的那些实现之间切换(例如,设备选择器或其他类似的东西。在示例中,这只是通过从主调用setter来完成的)。为了实现切换,我添加了一个类ImplementationDispatcher
,该类为隔离目的将一个shared_ptr
保留到当前实现中,类似于pimpl习惯用法。切换是通过向switcher类提供来自base的子类的新实例来完成的。
似乎是过度工程。只需实现您的抽象设备并将适当的实例传递给Work
。至少在您的示例中,根本不需要ImplementationDispatcher
。