我正在创建一个非常基本的Cache
对象。这里是我的代码:Java OOP多态设计/问题
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()
是protected
,该方法可以由类本身访问。我如何继续我想要做的事情?你如何改进我的实施?
编辑1:采取ControlAltDel和Turing85的建议,并与IoC一起去。我创建了一个名为BuildStrategy
的接口,它有一个void buildAndUpdate()
方法。它是否正确?
'Cache'类中的'buildAndUpdate'是抽象的,所以不能从'ACache'中调用,如果这是你所担心的。 – GriffeyDog
什么?它完全可以在'ACache'中调用。 'ACache'覆盖'buildAndUpdate()'方法,并且因为它是'Cache'中的'protected abstract',这意味着它在'ACache'中被覆盖时将具有'protected'修饰符。这就是问题所在。 – mpmp
暴露给谁? – biziclop