I am creating a very basic Cache object. Here is my code:
Cache.java is an abstract class meant to be overriden.
public abstract class Cache {
protected Date dateCreated;
protected long expiration;
private BuildStrategy strategy;
protected Cache(long expiration, BuildStrategy strategy) {
this.dateCreated = new Date();
this.expiration = expiration;
this.strategy = strategy;
strategy.buildAndUpdate();
}
private final boolean isExpired() {
long duration = new Date().getTime() - this.dateCreated.getTime();
if (duration > expiration) {
return true;
}
return false;
}
protected void build() {
if (!isExpired())
return;
setDateCreated(new Date());
buildAndUpdate();
}
protected abstract void buildAndUpdate();
final Date getDateCreated() {
return dateCreated;
}
final void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
final long getExpiration() {
return expiration;
}
final void setExpiration(long expiration) {
this.expiration = expiration;
}
}
This is a sample of a class that overrides it, ACache.java:
public class ACache extends Cache {
protected ACache(long expiration) {
super(expiration);
}
private Object variableToBeUpdated;
public Object getVariableToBeUpdated() {
return variableToBeUpdated;
}
public void setVariableToBeUpdated(Object variableToBeUpdated) {
this.variableToBeUpdated = variableToBeUpdated;
}
@Override
protected void buildAndUpdate() {
// ...connects to the database etc...
// ...once database stuff is done, update variableToBeUpdated
// NOTE: Other caches may implement buildAndUpdate() differently, that's
// why it's abstract
}
}
My problem here is that I want to hide the buildAndUpdate() method and just expose the build() method of Cache because in order for the Cache to be updated, I would want to check if it's expired first.
Since buildAndUpdate() is protected, the method can be accessed by the class itself. How do I proceed with what I want to do? How can you improve my implementation?
EDIT 1: Took ControlAltDel and Turing85's advice and went with IoC. I created an interface called BuildStrategy that has a void buildAndUpdate() method. Is this correct?
buildAndUpdatein theCacheclass is abstract, so it cannot be called fromACache, if that's what you're worried about.ACache.ACacheoverrides thebuildAndUpdate()method and since it'sprotected abstractinCache, that means it would have theprotectedmodifier when overriden inACacheThat's the problem.ACache.java,Cache.java,CacheManager.javaare all in the same package.