I'm capturing a network packet in my program as a char* array. The first byte of the array represents the type of packet I received and for each type I want to have a separate child class of my generic Packet base class to which I pass the byte array and where it will be interpreted.
I would like to avoid using a switch statement where the packet's first byte would be evaluated and the according constructor called. Firstly because in OOP you should avoid switch clauses and secondly because I don't want to add a separate case to the switch statement every time I add a packet class.
I looked into the Factory Method pattern, but I'm not sure how that would help me in this situation or if it would solve my problem at all.
Basically what I want to avoid is editing my code at 10 different places just to add a single packet class.
"I would like to avoid using a switch statement ..."
At some point you'll need to discriminate upon this byte, no matter if you're doing so in a factory or elsewhere.
A way to avoid switch, is to create a map of create_class functions, and find and call these according the map key (the discriminating byte value).
This solution will have the advantage, that you can easily add further keys and create_class functions, without changing the basic factory code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With