考虑一下此语法正确的伪代码(?):
class Event {
public:
virtual int getID() const = 0;
virtual int getSize() = 0;
virtual void* getData() = 0;
virtual void setData() = 0;
//(I cannot define data at this level 'cos I don't know what it is yet)
}
class SpecialEvent : class Event {
public:
virtual int getPGNID() const = 0;
int getSourceAddress() {return source_address;}
int setSourceAddress(int source_address) {this->source_address = source_address;}
protected:
int source_address;
}
template <typename T, typename E>
class EventWrapper : public E {
T data;
public:
static int EVENT_ID;
//implements everything in Event...EVENT_ID is assigned at runtime by some registry
}
class AnEvent : public EventWrapper<int, Event> {
//public methods specific to AnEvent...
}
class AnotherEvent : public EventWrapper<long, SpecialEvent> {
int getPGNID() const {static int ID = 10; return ID;}
}
class TheProcessingClass {
AnEvent event1;
AnotherEvent event2;
void process(Event& e);
void process(SpecialEvent& e);
void doSomething() {
process(event1); //should invoke process(Event&)
process(event2); //should invoke process(SpecialEvent&)
}
}
本质上,我有一个包装器类,它包装类型T的数据并从某种类型的
E
(在这种情况下为Event
或SpecialEvent
)继承。最初,我将创建两个包装器类
EventWrapper
和SpecialEventWrapper
,直到我发现这两个类将具有完全相同的代码(只要它是从某种类型的Event
扩展而来的)首先,这听起来像是基于策略的设计。但是,
Events
没有任何特殊行为...它们仅保存一些数据...我是否在滥用此模式?其次,还有更好的方法吗?我在这里大大简化了事情,但是任何见解都会受到赞赏...
编辑
我更新了示例...总而言之,处理类正在侦听事件,并且应基于事件采取措施。我希望这有帮助...
最佳答案
我建议添加process()作为类event的成员函数。
class Event {
int getID() const;
void process();
//class stuff
}
class SpecialEvent : class Event {
int getSpecialID() const;
void process(); //special version of process()
//class stuff
}
class TheProcessingClass {
Event event1;
SpecialEvent event2;
void doSomething() {
event1.process();
event2.process();
}
}