(Note: I'm not sure how to frame the question properly, so please feel free to edit it or comment about how I can improve it.)I guess this question, while covering a fairly wide scope, is pretty limited to statically typed (object-oriented) languages (I'm using Java in particular) for implementing CQRS and Event Sourcing. I've designed events pertaining to one particular aggregate as a hierarchy, in that they are subclasses of one parent class. Say I have an Order aggregate, and I have an OrderEvent base class whose subtypes are specific events like OrderPlaced, QuantityUpdated, OrderCancelled, etc.Now, inside this Order aggregate, I have overloaded apply methods that take specific subtypes of OrderEvent, like apply(OrderCancelled), and apply(QuantityUpdated). However, when reconstituting an Order object from the event source, what I have is a list of objects whose declared interface is just OrderEvent. Although technically, the underlying system keeps track of which specific subtype each of those objects are, there is no way in the code to imply that I've provided apply methods for each type specifically. I have to define a method that takes the parent OrderEvent class: apply(OrderEvent).Are there existent patterns around this that I'm not aware of? Or is something like the following the only option (written in Java):void apply(OrderEvent event) {    if (event instanceof OrderPlaced) {        apply((OrderPlaced) event);    }    if (event instanceof QuantityUpdated) {        apply((QuantityUpdated) event);    }    if (event instanceof OrderCancelled) {        apply((OrderCancelled) event);    }}I considered defining an applyTo method in the OrderEvent parent class/interface that takes an Order object to which the particular OrderEvent object gets applied to. For example:class OrderPlaced extends OrderEvent {    void applyTo(Order order) {        order.apply(this);    }}This will allow me to define apply(OrderEvent) in Order class as:void apply(OrderEvent event) {    event.applyTo(this);}It results in a more concise code, but I'm not so sure about the almost circular nature of the approach.What's the common pattern used for this?
How do I define a single generic method to apply events that are subtypes of a base class?
design patterns;object oriented design;domain driven design;cqrs;event sourcing