The Facade pattern defines a higher level class that
encapsulates and centralizes the interactions between Java
Persistence clients
and the model entities and operations of the Java Persistence
APIs. It provides a single interface
for operations on a set of entities. Using the Facade pattern
can make the code in
your Java Persistence clients cleaner. A web component using a Facade
does not have to be aware of all the details of the APIs for each
entity
and does not have to be aware of any persistence mechanisms being used
when accessing the entity managers or transaction managers. Introducing
a facade between the calling clients and the entities in
the model tier makes the code more loosely-coupled and easier to
maintain.
As code example 1 shows, the code with a facade is cleaner. Without using a facade, the client of the entities needs to know details about the entity and you might have similar code cut-and-pasted in other places whenever access to the entity was needed. The code after introducing a facade hides many of the details of the entities in the model tier.
Code Before | Code After Introducing a Facade |
public class MyWebClient ... {
//now access entities in model
tier
EntityManager em = |
...
MyModelFacade();
myfacade.addItem(item); |