《Head First Design Pattern》–開篇: 鴨子的故事

來源:互聯網
上載者:User
有各種各樣的鴨子(醬鴨、板鴨、黑頭鴨、野鴨、鹽水鴨...),特徵是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>>!  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.