命令設計模式的應用—自定義功能鍵
阿新 • • 發佈:2018-11-11
Sunny軟體公司開發人員為公司內部OA系統開發了一個桌面版應用程式,該應用程式為使用者提供了一系列自定義功能鍵,使用者可以通過這些功能鍵來實現一些快捷操作。Sunny軟體公司開發人員通過分析,發現不同的使用者可能會有不同的使用習慣,在設定功能鍵的時候每個人都有自己的喜好,例如有的人喜歡將第一個功能鍵設定為“開啟幫助文件”,有的人則喜歡將該功能鍵設定為“最小化至托盤”,為了讓使用者能夠靈活地進行功能鍵的設定,開發人員提供了一個“功能鍵設定”視窗,該視窗介面如圖所示:
1 找對應關係
功能鍵對應CommandSender,功能選項對應Command,功能對應CommandAccepter
2 設計CommandSender
public class FunctionKey{
private Command c;//功能鍵對應的命令
public FunctionKey(Command c){
this.c = c;
}
public void keyPressed(){
c.excute();
}
public void setCommand(Command c){
this.c = c;
}
}
3 設計Command
先寫一個介面:
public interface Command{
void excute();
}
命令的實現類:
public class CommandImpl implements Command{
private final Function f;//命令與功能繫結
public CommandImpl(Function f){
this.f = f;
}
public void excute(){
f.action();
}
}
4 設計Function
Function抽象類
public abstract class Function(){
public abstarct void action();
}
開啟幫助文件功能鍵
public class OpenHelpFile extends Function{ public void action(){ //open help file code here } }
其它功能鍵參照這個類