Refactor code to remove instanceof using double dispatch