[英]Class design question [optional implementation]
我想知道如何設計一個系統,其中有一個Super類和幾個Super子類(例如Sub1,Sub2,Sub3),而我想要一個Cool類。 現在我想擁有兩件事:
有什么建議么? 提示?
也許是這樣的:
class Super {}
interface Cool { boolean isCool(); }
class IsCool implements Cool {
public boolean isCool() { return true; }
}
class NotCool impolements Cool {
public boolean isCool() { return false; }
}
interface CoolSupporter {
boolean isCool();
Cool getCool();
}
class Sub1 extends Super implements CoolSupporter {
private Cool cool;
public Sub1() { this(new NotCool()); }
public Sub1(Cool cool) { this.cool = cool; }
public boolean isCool() { this.cool.isCool(); }
public Cool getCool() { return this.cool; }
}
class Sub2 extends Super implements CoolSupporter {
private Cool cool;
public Sub1() { this(new NotCool()); }
public Sub1(Cool cool) { this.cool = cool; }
public boolean isCool() { this.cool.isCool(); }
public Cool getCool() { return this.cool; }
}
class Sub3 extends Super {}
class CoolList {
private List<CoolSupporter> list = new ArrayList<CoolSupporter>();
public void add(CoolSupporter coolSupporter) {
if (coolSupporter.isCool()) {
list.add(coolSupporter);
} else {
throw new UncoolException();
}
}
}
Arne的答案可以滿足您的要求,但是我發現它過於復雜。 也許我缺少什么? 為什么不只是:
class Super { }
interface Cool { boolean isCool(); }
class CoolImpl extends Super implements Cool {
private boolean cool;
public CoolImpl(boolean cool) { this.cool = cool; }
public boolean isCool() { return this.cool; }
}
class Sub1 extends CoolImpl { }
class Sub2 extends CoolImpl { }
class Sub3 extends Super { }
class CoolList extends ArrayList<Cool> {
public boolean add(Cool cool) {
if (!cool.isCool()) {
return false;
}
return super.add(cool);
}
}
您可以創建一個很酷的標記界面。 讓類Sub1和Sub2實現此接口,並在添加到列表之前檢查cool實例
可能會有所幫助。
您不能在Java中有選擇地屬於某個類型的類。 盡管您可以繼承Sub1的子類,但其中一個子類實現接口Cool,而另一個子類則不實現:
class Super { }
interface Cool { }
class Sub1 extends Super { }
class Sub1Cool extends Sub1 implements Cool { }
class Sub2 extends Super { }
class Sub2Cool extends Sub2 implements Cool { }
class Sub3 extends Super { }
class CoolList extends ArrayList<Super> {
public boolean add(Super sup) {
if (!(sup instanceof Cool)) {
return false;
}
return super.add(cool);
}
}
您可能還會放棄酷概念並使用訪客模式:
class Super {
public boolean addTo(List<Super> coolList) {
if (canBeAddedToCoolList()) {
return coolList.add(this);
}
return false;
}
protected boolean canBeAddedToCoolList() {
return false;
}
}
class Sub1 extends Super {
protected boolean canBeAddedToCoolList() {
// check logic to allow/disallow addition
}
}
IMO,您需要有一個覆蓋列表(說MyList,它覆蓋add())。
在add()中,檢查要添加的對象是否為Cool,如果是,則將其添加到列表中。 如果不是,那么就優雅地忽略它。
這有幫助嗎?
管理此問題的最簡單方法是進一步擴展Sub1(CoolSub1和NotCoolSub1)和Sub2(CoolSub2和NotCoolSub2)的子類。
然后,CoolSub1和CoolSub2可以實現Cool(Cool應該是一個接口,而不是一個類)
然后您可以定義
List<Cool>
它將接受Sub1和Sub2的實現,但前提是它們必須實現Cool。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.