Hubidubi
Hubidubi

Reputation: 880

Calculation in entities

I have an @Entity. I want to make calculations on its fields. The problem is that I need to use extra constant parameters for some calculations that came from a @Service. How should I handle this problem? Probably I shouldn't autowire a service into a model.

Another option is to make a service for the model to handle all the calculations and store results in the model. I don't like it, because recalculations are more problematic and formulas are not stored together with the model.

Any idea?

Upvotes: 1

Views: 139

Answers (1)

erencan
erencan

Reputation: 3763

As far as i understand, you need to implement an adapter design pattern.

The adapter pattern is a structural design pattern. In the adapter pattern, a wrapper class (ie, the adapter) is used translate requests from it to another class (ie, the adaptee). In effect, an adapter provides particular interactions with an adaptee that are not offered directly by the adaptee.

You need to implement a adapter class which holds both your entity and parameters from your @Service (Adaptee1 and Adaptee2 in the UML) . Calculations can be done in the adapter methods (lets say methodA in the UML)

enter image description here

There is no need to set Adapter class to spring context. A dynamic instance can be created in the client code, most possibly in your @Service bean.

enter image description here

I find avajava design patterns tutorial simple and usefull, then i recommend you to have a look.

See also

Adapter Pattern avajava.com

Adapter Pattern

Examples of GoF Design Patterns

Upvotes: 1

Related Questions