美文网首页
根据传入参数不同调用不同的方法:命令模式

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

作者: 莫夏_b560 | 来源:发表于2019-07-16 22:19 被阅读0次

抽象的接口

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);
}

相关文章

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/drbxlctx.html