Re: [問題] abstract 的宣告與 polymorphic 新手問題

看板java作者 (骨頭)時間18年前 (2007/04/24 02:19), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串5/5 (看更多)
※ 引述《maxi326 (不想再留白)》之銘言: : ※ 引述《TonyQ (骨頭)》之銘言: : 謝謝兩位回答 : 就是多一步借父class來傳object進method : 裡面就發生多型去去判斷用那一個子class的method : decorater, state 這個好對我來說太進階了 : 我回頭再找這個的資料 : java版真是太棒了 : 謝謝大家 不見得要有method關係, 底下舉一個簡單例子來說。 當然由於懶得想的關係,所以沒設計成內部跳轉的例子, 不過你可以去找找糖果機的例子,不然鴨子也不錯。XD 大部分時候 state pattern是 自己轉換的。 我想多型的好處就是你不需要去管它是甚麼型態, //更正 應該說 不須了解細部的型態) 只需要就語意上去思考它的型別會做甚麼事情。 就像是Java一樣,你不用去想跨平台怎麼實作, 只要負責寫code,剩下的交給JVM去搞就是了。XD 底下簡單的例子 人剛醒的時候,自然還是會有點想睡。 肚子餓的時候,自然會去找食物。 沒事做的時候,自然會發呆。 雖然 me 做的事情都一樣 (thinking和action), 隨著狀態的變化(多型 , 因為都是personstate),而有不同的動作。 不過這應該也不算是個好例子(我也是初學者),看看就好。XD ──────────────────────────────── class PracticeOnly { public static void main( String[] arg ) throws Exception{ Person me=new Person(); me.setState(new wakeupstate()); me.thinking(); me.setState(new hungrystate()); me.action(); me.setState(new normalstate()); me.thinking(); me.action(); } } abstract class personState{ abstract void action(); abstract void thinking(); } class Person{ personState pstate; Person(){ pstate=new normalstate(); } void setState(personState p){ pstate=p; } void action(){ pstate.action(); } void thinking(){ pstate.thinking(); } } class wakeupstate extends personState{ void action(){ System.out.println("I just wake up !!"); } void thinking(){ System.out.println("I still wanna sleep...."); } } class hungrystate extends personState{ void action(){ System.out.println("I need to find food...(weakly)"); } void thinking(){ System.out.println("I am so hungry...."); } } class normalstate extends personState{ void action(){ System.out.println(" nothing to do "); } void thinking(){ System.out.println("idle...."); } } -- I am a person, and I am always thinking . Thinking in love , Thinking in life , Thinking in why , Thinking in worth. I can't believe any of what , I am just thinking then thinking , but worst of all , most of mine is thinking not actioning... -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.134.27.68 ※ 編輯: TonyQ 來自: 220.134.27.68 (04/24 02:25)
文章代碼(AID): #16BFYv8e (java)
討論串 (同標題文章)
文章代碼(AID): #16BFYv8e (java)