java servlets. Choosing a DAO in runtime
There is a web application. When you log in, we get to the login page, we will omit the logic of the application itself.
As a source of data about registered users, we use the Data Access Object template, namely the IUserDao interface, which has 2 implementations: DatabaseUserDao and let's say MemoryUserDao.
To get an instance, we use the UserFactory factory with the getClassFromFactory() method, which returns IUserDao.
How is it possible implement a servlet, in particular the init() method to be able to determine which IUserDao implementation to use? The idea is to avoid in-code initialization by a specific implementation:
IUserDao userDao = new DatabaseUserDao();
That's not good
Thanks!
2 answers
This is all done through the Strategy pattern. You define a lot of different implementations, then put them all in the container by key. In the right place, select the right DAO and that's it.
Example:
public interface Dao {
void execute();
}
public class DatabaseDao implements Dao {
@Override
public void execute() {
System.out.println("Database");
}
}
public class MemoryDao implements Dao {
@Override
public void execute() {
System.out.println("Memory");
}
}
public class Container {
private Map<String, Dao> container;
public Container() {
container = new HashMap<>();
container.put("database", new DatabaseDao());
container.put("memory", new MemoryDao());
}
public Dao getDao(String key) {
return container.get(key);
}
}
public class Application {
public static void main(String[] args) {
Container container = new Container();
container.getDao("memory").execute();
container.getDao("database").execute();
}
}
I'm not sure if I understood your task correctly, but I'll describe how I did it.
In the file db.properties
, set factory.class=model.dao.jdbc.JdbcDaoFactory
In the DaoFactory
class, I have a variable private static DaoFactory instance;
and a method that writes you an instance of the created factory to this variable. I have this public static DaoFactory getInstance()
. It initializes the variable instance = (DaoFactory) Class.forName(factoryClass).newInstance();
Variable String factoryClass = dbProps.getProperty("factory.class");
. Accordingly, changing the .properties
file, you substitute the factory you need.