有效实施命令模式

时间:2019-01-14 19:52:38

标签: java design-patterns command-pattern

初始代码:

public void updateState(final int state)
{
    preSet();
    itsState = state;
    postSet();
}
public void setTitle(final String title)
{
    preSet();
    itsTitle = title;
    postSet();
}

实施命令模式后:

public void updateState(final int state)
{
  CallableManager.doInTransaction(new Callable<Void>()
  {
     @Override
     public Void execute()
     {
       itsHiddenNodes = hiddenNodes;
       return null;
     }
  });
}
public void setTitle(final String title)
{
  CallableManager.doInTransaction(new Callable<Void>()
  {
     @Override
     public Void execute()
     {
       itsTitle = title;
       return null;
     }
  });
}

该接口是为pass方法创建的。

private interface Callable<T>
{
    public T execute();
}

创建此类来管理命令模式。

private class CallableManager
{
    public <T> static void doInTransaction(final Callable<T> callable)
    {
        preSet();
        callable.execute();
        postSet();
    }
}

如您所见,至少在本示例的代码行中,实现命令模式看起来并不十分有效。在此示例中,我实现了命令模式来避免重复的代码并减少代码行。但是结果是,在此示例中未同时提供它们。请给我一些建议。如何有效使用命令模式?

1 个答案:

答案 0 :(得分:4)

lambda可以大大减少代码重复。而且,Runnable似乎比Callable更合适,因为您没有返回值。

public class MainJava {
    private int state;
    private String title;

    public static void main(String... args) {
        MainJava mj = new MainJava();
        mj.setState(42);
        mj.setTitle("My Title");
    }

    public void setState(int state) {
        doInTransaction(() -> this.state = state);
    }
    public void setTitle(String title) {
        doInTransaction(() -> this.title = title);
    }

    private void doInTransaction(Runnable runnable) {
        preSet();
        runnable.run();
        postSet();
    }

    private void preSet() {
        System.out.println("preset");
    }
    private void postSet() {
        System.out.println("post-set");
    }
}