Posts

Showing posts from April, 2015

Design pattern visitor with java reflection

Image
What is the problem I have a collection of object of different type and i want add some behaviour without modify existing classes. More specific i want add different behaviour based on object's type. In our case i have objects of type Ferrari and Maserati and i want modify the property colour of this objects and print some message when i do that (this is the new behaviour). Due to this i want object of Ferrari in red and object of Maserati in blue. Class diagram Why use visitor Without the visitor i could create objects of type ConcreteElement and then modify this classes and recompile, but it it a bad idea. Or i could use if statement, something like: if object is of type Ferrari then do that, if is of type Maserati do that. But every time i add new type of object i need to modify that code. The visitor avoid the modification of that classes and allow to add different behavioural on each type of object. How visitor work Basically it work so: the client loop throug...