Re: [問題] 字串比較的問題
※ 引述《TonyQ (骨頭)》之銘言:
: 有個用空間換取時間的方法,
: 用String 作hash建表。
: 再直接對HASH後的內容處理:P
: 這個問題讓我想到State Pattern
: 不過要用在指令判定上 這可能不太適用..;p
用 Hash 是個好方法 :P
============================================================
// 建立一個命令的範本,用 toString 直接傳回命令的名稱
public abstract class AbstractCommand extends Object{
public void execute() {
}
// 懶得用 HashMap,只好改寫 toString 配合 HashSet
public String toString(){
StringBuffer buf = new StringBuffer();
buf.append(super.toString());
return buf.substring(0, buf.indexOf("@"));
}
}
============================================================
// 寫下你的命令要做些什麼
public class GetPizzaCommand extends AbstractCommand{
public void execute() {
System.out.println("Pizza ! Pizza!");
}
}
public class LookUpCommand extends AbstractCommand{
public void execute() {
System.out.println("Look it up");
}
}
============================================================
// 寫個 invoker
// 所有的 command instance 要加在 hash set 之內
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Invoker {
Set s;
public Invoker(HashSet s) {
this.s = s;
}
public void doIt(String cmd) {
for (Iterator it = s.iterator(); it.hasNext();) {
final AbstractCommand c = (AbstractCommand) it.next();
if (c.toString().equals(cmd)) {
c.execute();
break;
}
}
}
}
============================================================
// 主菜在這裡
import java.util.HashSet;
public class JustDoIt {
public static void main(String[] args) {
HashSet commandSet = new HashSet();
commandSet.add(new LookUpCommand());
commandSet.add(new GetPizzaCommand());
// add many commands you wanted
Invoker e = new Invoker(commandSet);
e.doIt("LookUpCommand");
e.doIt("No Such Command");
}
}
============================================================
有點麻煩的 switch case 不見了
會是仿造 Command Pattern 的設計,
因為想了一下如果用 Hash 要自己維護 Key 會有一點麻煩
多打字就增加打錯的機會,索性修改了 Command 的 toString
再弄個 Invoker 去執行我們的 command
即使沒有找到 command 或沒有這個 command 也不會有什麼錯誤而終止
會這樣設計的理由是,由您的語意來看
我感覺不到命令是前後相關的,所以沒有打算做 stateful 的設計
(DFA, state pattern ...if-goto etc.)
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.224.173.253
討論串 (同標題文章)