根据传入参数不同调用不同的方法:命令模式

2019-07-16  本文已影响0人  莫夏_b560

抽象的接口

public interface Command {
    Integer execute();
}

实现类

package com.baeldung.reducingIfElse;

public class AddCommand implements Command {

    private int a;
    private int b;

    public AddCommand(int a, int b) {
        this.a = a;
        this.b = b;
    }

    @Override
    public Integer execute() {
        return a + b;
    }
}

其它略

包装

  public int calculate(Command command) {
        return command.execute();
    }

测试demo

@Test
public void whenCalculateUsingCommand_thenReturnCorrectResult() {
    Calculator calculator = new Calculator();
    int result = calculator.calculate(new AddCommand(3, 7));
    assertEquals(10, result);
}
上一篇下一篇

猜你喜欢

热点阅读