The purpose of a Factory to allow a program to create an object instance that im
ID: 3849960 • Letter: T
Question
The purpose of a Factory to allow a program to create an object instance that implements an abstract interface. And it allows an easy way to substitute one implementation of the abstract interface for another.
In JPA, EntityManager is an example of an abstract interface. Both eclipse and hibernate are popular implementations of JPA. To use the eclipse implementation, you specify
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
in the persistence.xml. The application program executes the statement, Persistence.createEntityManagerFactory( ) which is a static method on the Persistence class. This method reads the persistence.xml file and loads the class from the eclipse implementation.
If you want to switch to Hibernate instead, no code in the application needs to change. Just modify the persistence.xml file to specify the hibernate implementation class.
Another useful pattern is the Singleton pattern. Creating an EntityManagerFactory involves a lot of CPU work; the persistence.xml file needs to opened, read, validated and parsed. The implementation class has to be loaded and database classes need to loaded as well.
An application only needs to do this once. A singleton pattern is used to ensure that only once instance of a particular object is created; in this example it would be EntityManagerFactory. If the application attempts to create another instance, the singleton does not create another instance, but rather return the previous instance already created.
Write a java class named EntityManagerSingleton that implements the singleton pattern for insuring only one instance of EntityManagerFactory is created by an application. Give an example of a servlet class that uses EntityManagerSingleton.
Explanation / Answer
Singleton Pattern :
Singleton pattern is a software design pattern. Singleton pattern ensures that only one object is created for a class.
The implementation for singleton pattern must be as follows:
CODE:
public class EntityManagerSingleton
{
Map<String,String> map=new HashMap<Integer,String>();
public EntityManagerFactory getEntityManagerFactoryObject(entityManagerFactoryOBJ) {
EntityManagerFactory entityManagerFactory=null;
// Checks if object is already in the map
if (map.containsKey(entityManagerFactoryOBJ)) {
// if exists then that object is copied to locally created one.
entityManagerFactory = (EntityManagerFactory) map.get(entityManagerFactoryOBJ);
} else {
//else create a new one.
entityManagerFactory=new EntityManagerFactory();
map.put("entityManagerFactoryOBJ", entityManagerFactory);
}
}
return entityManagerFactory;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.