2012-08-02 47 views
0

我是新來的「命令」設計模式,而且嘗試了它沒有真正知道我在做什麼。據我所知,這是不完全的堆棧溢出的適當的問題,但如果你看看我的源,它看起來像我接近它吧?我做了,因爲他們正在建造,執行任務的對象Java:作爲對象的行爲?繼承異常處理程序?

(編輯#1(而超類處理任何產生的異常。):這個來源是另一個類中,一個其字段包括「走出去」和「在」。)

public static interface Operations{ 
     public void action(String filename) 
      throws FileNotFoundException, UnsupportedEncodingException, IOException; 
    } 

    public static abstract class Operator implements Operations{ 
     public Operator(String filename){ 
      try{ 
       action(filename); 
      } catch(FileNotFoundException FNFE){ 
       sessionLog.report(FNFE.toString()); 
      } catch(UnsupportedEncodingException UEE){ 
       sessionLog.report(UEE.toString()); 
      } catch(IOException IOE){ 
       sessionLog.report(IOE.toString()); 
      } finally{ 

       try{ 
        out.close(); 
       } catch(IOException IOE){ 
        sessionLog.report("The file may not have closed properly. "+IOE.toString()); 
       } catch(NullPointerException NPE){ 
        //sessionLog.report("The file may be null."); 
       } 
      } 
     } 
    } 

    public static class Saver extends Operator{ 
     public void action(String filename) 
       throws FileNotFoundException, UnsupportedEncodingException, IOException{ 
      out = new OutputStreamWriter(new FileOutputStream(filename), ENCODE); 
      out.write("Spoons."); 
     } 
     public Saver(String filename){super(filename);} 
    } 

    public static class Opener extends Operator{ 
     public void action(String filename) 
       throws FileNotFoundException, UnsupportedEncodingException, IOException{ 

      in = new InputStreamReader(new FileInputStream(filename), ENCODE); 
      /* ... */ 
     } 
     public Opener(String filename){super(filename);} 
    } 

    public static void save(String filename, ShoppingMutableTreeNode SMTN){ 
     new Saver(filename); 
    } 

    public static void open(String filename){ 
     new Opener(filename); 
    } 

回答

1

你的實現看起來好像沒什麼問題。一對夫婦的建議,但:

我就會改掉文件名參數的行動(),因爲這將讓我做這樣的事情

new Saver("file1.txt").action("file2.txt"); 

我也擺脫動作()調用構造函數。我不認爲大多數開發商會推斷,構造函數沒有被挖掘到您的源代碼進行實際的行動 - 它只是似乎並不直觀。這樣的事情會更明確:

public abstract class Operation implements ... { 
    private String filename; 

    public Operation(String filename) { this.filename = filename; } 

    public abstract void execute(); 
} 

那麼你的代碼可以調用它

new SaveAction("myfile.txt").execute(); 

最後一個快字上Command模式 - 你在這裏用它來分享異常處理。這真的讓我想起了更多的Template模式。

格局的力量真的來自於事實,你有抽象行爲和不知道它在運行時什麼確切的行動執行它們。這裏有一些用途的模式:http://en.wikipedia.org/wiki/Command_pattern#Uses

+0

謝謝!這非常豐富,正是我需要的! – 2012-08-03 16:54:03