
AMDG Asif Lodhi wrote:
Hi Steven,
On 3/30/08, Steven Watanabe <watanabesj@gmail.com> wrote:
......................................................... There needs to be a way to register callbacks for each particular event type. Then, there is some code that gets a packet and decodes it to the proper type. Finally, this is dispatched to all the registered signals.
That's exactly why I suggested using the Observer design pattern.
How is anything suggested in this thread not an instance of Observer, I might ask? I guess the problem is: where do the callbacks get registered? You can't register them with the event because the event doesn't exist yet. You can create a global object to register for each Packet type, but globals are not usually a good idea. It is also possible to have a separate object for each type of Packet, but they are all tightly bound together and all need to be available when the Packet comes in. This leads to having one class that holds all the callbacks. Now, we could create a separate signal for each Packet type in the class body: class SignalHolder { public: void operator()(const Packet1& packet) const { signal1(packet); } void operator()(const Packet2& packet) const { signal2(packet); } void operator()(const Packet3& packet) const { signal3(packet); } ... void operator()(const PacketN& packet) { signalN(packet); } private: signal<void(Packet1 const&)> signal1; signal<void(Packet2 const&)> signal2; signal<void(Packet3 const&)> signal3; ... signal<void(PacketN const&)> signalN; }; class Packet { virtual void dispatch(const SignalHolder&) = 0; }; class Packet1 : public Packet { virtual void dispatch(const SignalHolder& visitor) { visitor(*this); } }; The only real difference between this and the map solution is that this may be slightly faster and has one more component that needs to be updated when a new packet type is added. If you have a better way of doing this in mind, let me know. In Christ, Steven Watanabe