Design a Java POJO with lazy loading property

前端 未结 2 1921
悲&欢浪女
悲&欢浪女 2021-01-21 01:58

Please consider below example:

A web application creates a user object for every logged in user. This object has simple String properties for firstNam

2条回答
  •  灰色年华
    2021-01-21 02:33

    Instead of a reference to a car, you could use a reference to a car supplier object whose implementation could cache the first result obtained (see Guava's Supplier and MemoizingSupplier classes). By doing so, you hide from the User object the fact that its car might or might not be present at instantiation time, and therefore make its implementation simpler (no more logic in the getter method).

    Another advantage of this solution would be to break the coupling between the User and the CarServices classes (no need for the carServices property anymore). One could inject a supplier whose implementation would return a reference to an already available Car object, while another could pass an implementation that forwards the call to a CarServices service.

    It wouldn't make the User class more of a POJO though (as explained in the first answer above), but people who have argued with your solution might like this one better because of it being simpler and less tightly coupled.

提交回复
热议问题