策略模式实现

策略模式:

策略模式是一种行为型设计模式,它允许你定义一系列算法,把它们封装起来,并且使它们可以互相替换。这样,使用算法的客户端代码可以独立于具体的算法实现方式。

就好像是你要去旅行,你可以选择多种不同的交通工具(比如汽车、飞机、火车),每种交通工具都是一种策略。你根据自己的需求和情况选择最适合的交通方式,这就是策略模式的思想。

在策略模式中,通常有三个角色:

  1. 上下文(Context):包含一个策略对象,负责和客户端交互。上下文知道策略对象,并能根据需要调用具体的策略来完成任务。
  2. 策略接口(Strategy Interface):定义了一系列算法的共同行为。通常是一个接口或者抽象类,规定了具体策略类所必须实现的方法。
  3. 具体策略类(Concrete Strategies):实现了策略接口,在具体的策略类中实现了算法。

同样的,来实现一个计算器,他拥有加法、减法、乘法等运算。

策略接口

java 复制代码
public interface BaseStratege {
    int compute(int x,int y);
}

具体策略类

java 复制代码
class Add implements BaseStratege {

    @Override
    public int compute(int x, int y) {
        return x+y;
    }
}

class Sub implements BaseStratege {

    @Override
    public int compute(int x, int y) {
        return x-y;
    }
}

上下文Context

java 复制代码
public class Context {

    private BaseStratege stratege;

    public Context(BaseStratege stratege) {
        this.stratege = stratege;
    }

    public int compute(int x,int y){
        return stratege.compute(x,y);
    }

    public BaseStratege getStratege() {
        return stratege;
    }

    public void setStratege(BaseStratege stratege) {
        this.stratege = stratege;
    }
}

和工厂模式类似,同样先创建一个接口,然后创建对应的实现类,再使用一个Context类来计算结果,但是Context中获取特定实现类的操作,是需要我们手动给定的,也就是说策略模式需要我们记住所需的实现类

java 复制代码
 public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int x = scanner.nextInt();
        int y = scanner.nextInt();
        int result = new Context(new Add()).compute(x, y);
        System.out.println(result);
    }

以上的 Add()类就是需要我们记住的,而不是像工厂一样只需要给定一个特定的条件.

总结:

​ 工厂模式和策略模式在形式上比较相似,但是在实际使用场景中有很大的不同,工厂模式用在能通过某些条件得到确定的实现类,策略模式用在需要我们来判断所需的实现类。

相关推荐
〆、风神1 天前
策略模式与元数据映射模式融合 JSR 380 验证规范实现枚举范围校验
windows·spring·策略模式
码界孔乙己4 天前
python策略模式
python·策略模式
此木|西贝4 天前
【设计模式】策略模式
设计模式·策略模式
患得患失9496 天前
【设计模式】策略模式(Strategy Pattern)详解
设计模式·bash·策略模式
一恍过去7 天前
SpringBoot通过Map实现天然的策略模式
spring boot·后端·策略模式
Vic101017 天前
Java 中装饰者模式与策略模式在埋点系统中的应用
java·开发语言·策略模式
獨枭7 天前
在 macOS 上配置 VS Code 使用 PowerShell(适配 Homebrew 安装)
macos·策略模式
cijiancao8 天前
23种设计模式中的策略模式
设计模式·策略模式
罗帅·迪克劳纳8 天前
SpringBoot+策略模式+枚举类,优雅消除if-else
java·spring boot·后端·策略模式
Antonio9159 天前
【Q&A】策略模式在QT有哪些应用
开发语言·qt·策略模式