I am working on a parser for a serial data protocol. I have an overarching Packet class, a couple sub-classes such as CommandPacket and StatusPacket, and then a few sub-classes of each of those:
- Packet
-
- CommandPacket
-
-
- CommandTypeA
-
-
-
- CommandTypeB
-
-
- Status Packet
-
-
- StatusTypeA
-
-
-
- StatusTypeB
-
The Packet class has a static method for taking data off of a buffer, and if it represents a valid packet, returning a new instance of the Packet class, instantiated with the necessary data.
Now, this is where my problem comes up. I would like to be able to return the most specific type of packet. To facilitate this, I have created a static .isValid() method, which is overridden on the sub classes. The idea is that I could loop through each type of specific packet (CommandTypeA, CommandTypeB, StatusTypeA, StatusTypeB, etc.) calling .isValid() until one of them returned TRUE. At that point, I would return a new instance of that specific packet type.
While of course it is possible for me to create this method directly, how do I account for types of packets that are not added to my project yet? I want someone to be able to extend my class in the future without having to modify the original Packet class.
I have considered utilizing reflection for this, but am avoiding it, since these methods would be called for each and every packet received, and must be efficient.
Any thoughts on how I should re-work my design pattern?
While I don’t think it is entirely relelvant to the discussion, I am doing this in VB.NET. There is also a similar (but not quite the same) question posted here: Java – subclass validation design pattern
Based on the comments and MarkJ’s lead, here’s a suggestion (which is eventually based on an interface instead of an attribute for stronger type checking):