2012-08-02 40 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