有各種各樣的鴨子(醬鴨、板鴨、黑頭鴨、野鴨、鹽水鴨...),特徵是Quack(嘎嘎叫),Swim(遊水)。於是定義的一個SuperDuck(父類),裡面有方法Quack、Swim、Display顯示!子類比如黑頭鴨、RedHeadDuck,重寫Display方法! But Now We need the ducks to Fly!How to do?(鴨子要可以飛,怎麼辦?) I Just need to add a fly() method in the SuperDuck(父類),then all the ducks will inherit it.Now's my time to really show my true OO genius!(我真是個OO的天才啊,哈哈!) They just give a demo and there were rubber duckies flying around the screen!Was this idea of a joke?
(他們只不過做了一個讓好多橡皮的鴨子滿螢幕飛的示範!這是在開玩笑嗎?) 不是所有的鴨子都能飛的呀!!! Thinks about inheritance(考慮一下繼承)我可以在RubberDuck(橡皮鴨)中重寫Fly的方法。 But then what happens when wu add wooden decoy ducks(木頭鴨),它既不能Quack叫,也不能Fly。在木頭鴨重寫Quack()、Fly()???? How about a interface?I could take the fly() out of the SuperDuck(父類),and make a flyable() interface with a fly() method. That way,only the ducks that are supposed to fly will implement that interface and have a fly() method....and I might as well make a Quackable(嘎嘎),too,since not all the ducks can quack!(介面怎麼樣?我可以把Fly從父類中剝離出來,變成一個介面,如果有鴨子可以飛,那麼這隻鴨子就實現這個介面。 Quack(嘎嘎叫)也是類似的.) That is , like , the dumbest idea you've come up with.Can you say "duplicate code"?If you thought having to override a few methods was bad,How are you gonna feel when you need to make a little change to the flying behavior... in all 48 of the flying Duck subclass?!(現在你可以說copy代碼。那麼我們如果對flying 有一個小小的改變怎麼樣?所有48個用到這個介面的子類都要改變一下,Copy48份?????) How we can do next???到底該怎麼辦?Please be with <<Head First Design pattern>>!