更好地整合多种类型接口的方法
我有两个设备。
class Device1{
public:
int GetData(){
//...
}
};
class Device2{
public:
bool GetData(){
//...
}
};
我有AA C#样式计时器类,可以定期运行std ::线程。 时间到了,我只会显示一次一次电话,而不是周期性的电话。
计时器类看起来像这样:
class Timer {
public:
Timer(long long period,
std::function<int()> f):
m_timeperiod(period * 1000000){
m_enable = true;
m_thd = std::thread (f);
}
virtual ~Timer(){}
void Wait()
{
m_thd.join();
}
private:
long long m_timeperiod;
std::atomic<bool> m_enable;
//std::function <int()> m_action;
void Loop();
std::thread m_thd;
};
主要看起来像:
int main()
{
Device1 d1;
std::function<int()> fnCaller = std::bind(&Device1::GetData, &d1);
Timer tmr(1,fnCaller);
tmr.Wait();
std::cout<<"Hello World";
return 0;
}
这对Device1工作正常,但是我必须为Device2创建一个新的计时器类2。
class Timer2 {
public:
Timer(long long period,
std::function<bool()> f):
m_timeperiod(period * 1000000){
m_enable = true;
m_thd = std::thread (f);
}
virtual ~Timer(){}
void Wait()
{
m_thd.join();
}
private:
long long m_timeperiod;
std::atomic<bool> m_enable;
//std::function <int()> m_action;
void Loop();
std::thread m_thd;
};
稍后,我可能需要为Device3创建一个较新的版本,例如,依此类推。 我该怎么做才能有一个可扩展的解决方案?
I have, say, two devices.
class Device1{
public:
int GetData(){
//...
}
};
class Device2{
public:
bool GetData(){
//...
}
};
I have a a C# style timer class that runs a std::thread periodically.
Time being, I am showing only a one-time call, rather than the periodic ones.
A Timer class looks like this:
class Timer {
public:
Timer(long long period,
std::function<int()> f):
m_timeperiod(period * 1000000){
m_enable = true;
m_thd = std::thread (f);
}
virtual ~Timer(){}
void Wait()
{
m_thd.join();
}
private:
long long m_timeperiod;
std::atomic<bool> m_enable;
//std::function <int()> m_action;
void Loop();
std::thread m_thd;
};
The main looks like:
int main()
{
Device1 d1;
std::function<int()> fnCaller = std::bind(&Device1::GetData, &d1);
Timer tmr(1,fnCaller);
tmr.Wait();
std::cout<<"Hello World";
return 0;
}
This works fine for Device1, but I have to create a new Timer class for Device2.
class Timer2 {
public:
Timer(long long period,
std::function<bool()> f):
m_timeperiod(period * 1000000){
m_enable = true;
m_thd = std::thread (f);
}
virtual ~Timer(){}
void Wait()
{
m_thd.join();
}
private:
long long m_timeperiod;
std::atomic<bool> m_enable;
//std::function <int()> m_action;
void Loop();
std::thread m_thd;
};
Later I might need to create a newer one for Device3, so on and so forth.
What can I do to have a scalable solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论