如何避免 java 中的半重复方法组?

How can I avoid semi-repeating groups of methods in java?

假设我写了以下方法:

public void submitForm1() {
        open();
        setField(1, "blah");
        setField(3, "bla");
        setField(4, "blah blah");
        submit();
    }

public void submitForm2() {
        open();
        setField(1, "blah");
        checkBox(1 , true);
        submit();
}

....

public void submitForm100() {
        open();
        setField(1, "bla");
        setField(2, "bla bla");
        setField(3, "blah");
        setArea(1, "blah blah");
        submit();
}

这些方法让我觉得我在不断地重复自己。我觉得应该这样写:

public void submitForm1() {
        MyMethods.submitForm(
            {SET_FIELD, 1, "blah"},
            {SET_FIELD, 3, "bla"},
            {SET_FIELD, 4, "blah blah"}
        );
    }

public void submitForm2() {
        MyMethods.submitForm(
            {SET_FIELD, 1, "blah"},
            {CHECKBOX, 1, true}
        );
}

....

public void submitForm100() {
        MyMethods.submitForm(
            {SET_FIELD, 1, "bla"},
            {SET_FIELD, 2, "bla bla"},
            {SET_FIELD, 3, "blah"},
            {SET_AREA, 1, "blah blah"},
        );
}

这样我就不必一遍又一遍地重复所有这些打开和提交方法。

有办法吗?

我不这么认为,但你为什么不这样做:

public void submit() {
  open();
  switch(formNumber) {
    case 1:
    submitForm1();

    case 2:
    submitForm2();

    case 100:
    submitForm100();

    default:
    break;
  }
  submit();
}

您可以使用类似的东西:

public interface FormSubmission {
  void set();
  default submitForm() {
    open();
    set();
    submit();
  }
}

那么您的代码将如下所示:

Map<Integer, FormSubmission > forms = new HashMap<> ();

//in constructor or static initialisation block:
forms.put(1, () -> { setField(1, "blah");
                     setField(3, "bla");
                     setField(4, "blah blah"); });
//etc.

public void submitForm(Integer i) {
  forms.get(i).submitForm(); //probably want to handle NPE here
}

类似于命令模式

你可以用"callback"举例。为此,请执行以下操作:

void doInSubmit(SubmitCallback callback)
{
    open();
    callback.call();
    submit();
}

外面:

public void submitForm100() 
{
    doInSubmit(new SubmitCallback() 
    {
        void call()
        {
            setField(1, "bla");
            setField(2, "bla bla");
            setField(3, "blah");
            setArea(1, "blah blah");
        }
    })        
}