作者TonyQ (骨头)
看板java
标题Re: [问题] abstract 的宣告与 polymorphic 新手问题
时间Tue Apr 24 02:19:35 2007
※ 引述《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)