當我們要對某一個對象進行一系列操作的時候,通常要怎麼做呢?
比如對一個“電腦”對象進行打字操作,一般的流程是這樣的:
computer.power();//通電開機
computer.setInputMethod();//設置輸入法
computer.pressKey();//敲擊鍵盤打字
這類操作寫下來。。。代碼就變得不優雅了呀!!!而且隨着你的操作越來越多,這些代碼會越來越長。並且如果在其它地方很難直接複用。
那麼如何優雅的解決這類問題呢?
定義一個鏈表操作對象!!!
首先我們定義一個Op類
public final class Op{
Op next;
String cmd;
}
再寫一個執行Op對象的方法
public void execOp(Op op){
if(op == null) return;
switch(op.cmd) {
case "power":
computer.power();
break;
case "inputMethod":
computer.setInputMethod();
break;
case "pressKey":
computer.pressKey();
break;
}
execOp(op.next);//在這裏自己調用自己
}
通過這種方式我們再處理操作的時候不就更方便了嗎?代碼不就優雅了嗎?而且代碼的複用性也增加了,嗯真香
當然這個時候肯定有小夥伴會說,那這個東西創建Op指令的時候也是一樣的麻煩啊。。。怎麼會呢?
簡直優雅的不要不要的好嗎
public Op createOp(String...cmds){
if(cmd == null) return null;
Op opPre = new Op();
Op op = opPre;
for (String s:cmds) {
if (op.next == null) op.next = new Op();
op.next.cmd = s;
op = op.next;
}
return opPre.next;
}
將指令作爲數組傳進去,然後就能得到一個Op鏈表命令,再通過execOp方法去執行完成。。。優雅的不行呀