Java:作为对象的动作?继承异常处理程序?

时间:2012-08-02 15:41:26

标签: java design-patterns command

我是“命令”软件设计模式的新手,我在不知道自己在做什么的情况下尝试了它。我知道这对Stack Overflow来说不是一个合适的问题,但是如果你看一下我的来源,它看起来好像我正在接近它吗?我已经创建了在构造它们时执行任务的对象(而超类处理任何引发的异常。)

(编辑#1:此来源位于另一个类中,其中的字段包含“out”和“in”。)

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 个答案:

答案 0 :(得分:1)

您的实施对我来说很好。但有几点建议:

我会删除action()的filename参数,因为它会让我做类似

的操作
 new Saver("file1.txt").action("file2.txt");

我也会在构造函数中删除action()调用。我不认为大多数开发人员会推断构造函数在没有深入挖掘源代码的情况下执行实际操作 - 这似乎并不直观。这样的事情会更明确:

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

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

    public abstract void execute();
 }

然后你的代码可以调用它

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

关于命令模式的最后一个简单的说法 - 您在此处使用它来共享异常处理。这真的让我想起了Template模式。

模式的强大之处在于你拥有抽象动作并执行它们而不知道它在运行时的确切动作。以下是模式的一些用法:http://en.wikipedia.org/wiki/Command_pattern#Uses