设计模式—策略模式

介绍

在策略模式(Strategy Pattern)中一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。

在策略模式定义了一系列算法或策略,并将每个算法封装在独立的类中,使得它们可以互相替换。通过使用策略模式,可以在运行时根据需要选择不同的算法,而不需要修改客户端代码。

代码

策略接口

public interface Strategy {
    public int doOperation(int num1, int num2);
}

策略实现

OperationAdd

public class OperationAdd implements Strategy{
    @Override
    public int doOperation(int num1, int num2) {
        return num1 + num2;
    }
}

OperationMultiply

public class OperationMultiply implements Strategy{
    @Override
    public int doOperation(int num1, int num2) {
        return num1 * num2;
    }
}

OperationSubtract

public class OperationSubtract implements Strategy{
    @Override
    public int doOperation(int num1, int num2) {
        return num1 - num2;
    }
}

测试

编写一个执行者类 Executor,包含策略属性

class Executor {
    private Strategy strategy;

    public Executor(Strategy strategy) {
        this.strategy = strategy;
    }

    public int executeStrategy(int num1, int num2) {
        return strategy.doOperation(num1, num2);
    }
}

编写测试代码,让执行者执行不同的策略

public class StrategyTest {
    @Test
    void test() {
        Executor executor = new Executor(new OperationAdd());
        Assertions.assertEquals(executor.executeStrategy(1, 2), 3);

        executor = new Executor(new OperationSubtract());
        Assertions.assertEquals(executor.executeStrategy(1, 2), -1);

        executor = new Executor(new OperationMultiply());
        Assertions.assertEquals(executor.executeStrategy(1, 2), 2);
    }
}
posted @ 2023-12-20 10:48  Frodo1124  阅读(10)  评论(0编辑  收藏  举报