Say I have a package with classes taken from a domain model. They have no knowledge of any UI (coordinates, ...). Say I want to draw each of these classes in their own, characteristic way. Each 'way to draw' is represented by a class.
Say I want to know how to draw a certain class. I can ask the class itself how it would like to be drawn (method -getGraphic
) and then use the returned object to do the drawing itself. But then the class knows about drawing, and I want to avoid that. This is the Factory Method pattern, relying on polymorphism.
So what I could do is, in the class responsible for the drawing itself, check the type of the class that is to be drawn, and then determine there what way it should be drawn.
But instanceof would cause issues when many new subclasses would be added, all classes that are drawn in characteristic ways. I'd need a lot of conditional logic. Not only that, but if many classes do drawing, they would all need that logic.
This is a problem I often encounter ; having to resort to type checking because polymorphism is not appropriate (in this case it leads to coupling, mixing UI/domain layer). Is there a proper way to address it? Is there a design pattern for it?
There is a question with a similar title here.
Aucun commentaire:
Enregistrer un commentaire