Creating a DataAccessStrategyManager Wrapper
While calling the DataAccessStrategyManager is straight-forward, typos are still possible. As such, it is often easier to make a wrapper for your application that hides any references to strings or constants. And writing a wrapper is very simple.
If you only use one strategy ...
If you only use one strategy (for instance, only JDBC or only Hibernate3), you can write a simple wrapper like this:public class DataAccessManager {
public static final String APP_NAME = "yourapp";
public static DataAccessStrategy getDataAccessStrategy() {
try {
DataAccessStrategy das = DataAccessStrategyManager.getStrategy(APP_NAME,
DALConfigurationConstants.JDBC_DAS_NAME);
if (das == null) {
throw new RuntimeException("DAS was null. Check your configuration.");
}
else {
return das;
}
}
catch (Exception ex) {
throw new RuntimeException(ex.getMessage());
}
}
As you can see, very straightforward. And it hides the need to understand the manager's interface from the rest of your code.
If you use two or more strategies ...
If you use two or more strategies (for instance, both JDBC and Hibernate3), you can write a simple wrapper like the one in the single example:public class DataAccessManager {
public static final String APP_NAME = "yourapp";
public static DataAccessStrategy getJdbcStrategy() {
try {
DataAccessStrategy das = DataAccessStrategyManager.getStrategy(APP_NAME,
DALConfigurationConstants.JDBC_DAS_NAME);
if (das == null) {
throw new RuntimeException("DAS was null. Check your configuration.");
}
else {
return das;
}
}
catch (Exception ex) {
throw new RuntimeException(ex.getMessage());
}
}
public static DataAccessStrategy getHibernate3Strategy() {
try {
DataAccessStrategy das = DataAccessStrategyManager.getStrategy(APP_NAME,
DALConfigurationConstants.HIBERNATE3_DAS_NAME);
if (das == null) {
throw new RuntimeException("DAS was null. Check your configuration.");
}
else {
return das;
}
}
catch (Exception ex) {
throw new RuntimeException(ex.getMessage());
}
}
As you can see, very straightforward.
PLEASE NOTE: Instead of returning the specific strategy type, we still return the DataAccessStrategy type. It is highly recommended you follow this convention. You want to use the standard DAS interface whenever possible--this enables your code to stay implementation neutral. If you need an implementation specific method, cast down to the type and do so with care. By doing so, you are tying your code to a specific implementation.
/rsh tech
