samedi 13 mai 2017

Java - Arithmetic expression with composite + Visitor that calculates derivative

I've got this OOP () exercise in preparation for an exam, and I am actually stuck on an apparently simple task:

Write a hierarchy that represent an arithmetic expression made of sums, products, constant and a (unique) variable. Make the Composite visitable and write a that, given an expression, return its derivative.
In the end, write the function MyApp that generates an object that represents the function 2(x^2)-3 (I think it implicitly means y=2(x^2)-3, Ed.) and calculates his derivative.

The last part (MyApp creation) can be omitted from the problem.

So my basic knowledge tells me to create an interface "Expression" that would be implemented by multiple classes: Sum, Product, Constant, Variable.

Then I need to create an interface "Visitor" that would be implemented by multiple visitor classes: SumVisitor, ProductVisitor, ConstantVisitor, VariableVisitor, that calculate the derivative of each expression and return it as an Expression.

If I want to do this, I also must make the composite visitable by creating an accept(Visitor visitor) method, but this is where I get stuck, because I can't understand it very well (where to put the method? must ovverride it? etc).

I've already googled it but I can't apply what I found about composite-visitors to this exercise.

This is not homework, just an exercise I want to solve in order to understand patterns better, and I really need so if I want to pass the exam.

Hope you can give me some hint (or your personal solution, I don't mind).

Thank you.

Aucun commentaire:

Enregistrer un commentaire