Imagine I have an object that could be any of a number of different types that all derive from a single base type. I want to create a second object which is related to the first object in the sense that its type is dependant on the type of the first object. The type of the second object will however always derive from a second base class.
My go to solution would be to have the first object create the second object through a virtual method.
In this particular situation however, we do not want the two classes to be coupled at all. Neither object should have any existence of the other object.
This means there must be some kind of third-party mediator object creating the second object based on the first objects type.
My next chosen solution would therefore be to have this mediator be a factory which looked specifically at the type of the first object and instantiated the second object based upon it.
To me this works, but seems not an ideal solution. If a factory is creating the first object then whenever a new derived type is added two factories must be updated and a new connection made.
Are there any common design patterns that could help with this and make the code cleaner?
Aucun commentaire:
Enregistrer un commentaire