我正在创建一个非常基本的Cache
对象。这是我的代码:
Cache.java
是一个需要重写的抽象类。
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;
}
}
这是重写它的类的示例,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
}
}
我的问题是我想隐藏 buildAndUpdate()
方法并只公开 Cache
的 build()
方法,因为在为了更新 Cache
,我想先检查它是否已过期。
由于 buildAndUpdate()
受保护
,因此该方法可以由类本身访问。我该如何继续我想做的事情?您如何改进我的实现?
编辑 1:采纳 ControlAltDel 和 Turing85 的建议并选择 IoC。我创建了一个名为 BuildStrategy
的接口(interface),它有一个 void buildAndUpdate()
方法。这是正确的吗?
最佳答案
您可以采取的一种方法是完全摆脱此方法,而是在 BuildAndUpdate 类中创建,这将是构造函数中的必需参数。然后,您可以对 Cache 类进行子类化,并在空构造函数中,使用 BuildAndUpdate 对象初始化父类(super class)。
有道理吗?
关于Java OOP多态设计/问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30491687/