昨天看了一下反模式,居然發(fā)現(xiàn)call super也是其中一種,所謂的call super就是在子類的重載方法中去調(diào)用父類的被重載的方法,說的通俗點,就是在方法中調(diào)用super.xxx(). 這種寫法在Java中真是太普遍了,且不說Java的構(gòu)造方法會自動調(diào)用父類的構(gòu)造方法,我們自己也是經(jīng)常在用super.xxx()。為什么它是一種反模式,卻又用的如此普遍呢?
為什么不提倡用super,Martion Flower是這么解釋的:Whenever you have to remember to do something every time, that's a sign of a bad API. Instead the API should remember the housekeeping call for you. 就是說不能讓子類老是記得要調(diào)用super.xxx, 你的API設(shè)計應(yīng)該幫你調(diào)用。為此,他建議用template method pattern。比如:
public class EventHandler ...
public void handle (BankingEvent e) {
housekeeping(e);
}
public class TransferEventHandler extends EventHandler...
public void handle(BankingEvent e) {
super.handle(e);
initiateTransfer(e);
}
可以改成:
public class EventHandler ...
public void handle (BankingEvent e) {
housekeeping(e);
doHandle(e);
}
protected void doHandle(BankingEvent e) {
}
public class TransferEventHandler extends EventHandler ...
protected void doHandle(BankingEvent e) {
initiateTransfer(e);
}
但是用模板方法也有它的局限性,它要求改動父類代碼,如果你是擴展某些API,那那些父類代碼不見得能隨便修改。再加上super.xx()非常直觀明了,我想這也是super call仍然被廣泛使用的原因吧。
posted on 2009-09-02 16:28
Aaron.Chu 閱讀(234)
評論(0) 編輯 收藏