我正在創建一個非常基本的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