设计模式-行为型模式-策略模式

策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。DP

复制代码
//首先,我们定义一个策略接口:


public interface Strategy {
    public int doOperation(int num1, int num2);
}
//接着,我们创建实现了策略接口的具体策略类:


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

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

public class OperationMultiply implements Strategy {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 * num2;
    }
}
//然后,我们创建一个上下文类,它接受一个策略对象并使用该策略对象执行操作:


public class Context {
    private Strategy strategy;

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

    public int executeStrategy(int num1, int num2) {
        return strategy.doOperation(num1, num2);
    }
}
//最后,我们编写客户端代码来演示如何使用策略模式:


public class StrategyPatternDemo {
    public static void main(String[] args) {
        Context context = new Context(new OperationAdd());    
        System.out.println("10 + 5 = " + context.executeStrategy(10, 5));

        context = new Context(new OperationSubtract());    
        System.out.println("10 - 5 = " + context.executeStrategy(10, 5));

        context = new Context(new OperationMultiply());    
        System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
    }
}
相关推荐
董员外13 小时前
RAG 系统进化论(八):Agentic RAG(智能体式 RAG),从回答问题到完成任务
人工智能·后端·设计模式
董员外18 小时前
RAG 系统进化论(七):Multimodal RAG(多模态 RAG),当知识存在于表格、图片和页面中
人工智能·后端·设计模式
大山同学18 小时前
第 2 篇(03-04 章):代理设计原则与工具使用设计模式
设计模式
赶路人儿20 小时前
MacOS 下实现 AI 操控电脑(Computer Use)的思考
人工智能·macos·策略模式
Fozei21 小时前
录屏原理与鼠标可视化
计算机外设·策略模式
啦啦啦啦啦zzzz2 天前
设计模式:桥接模式和组合模式
c++·设计模式·组合模式·桥接模式
莫得感情 o2 天前
设计模式 03 · 工厂方法模式
设计模式·工厂方法模式
cyforkk2 天前
高并发核心设计模式:Single-Flight 原理与实战
设计模式
饼干哥哥3 天前
字节Seedance2.5终于上线,这次在收割谁?
人工智能·设计模式·前端框架
董员外3 天前
RAG 系统进化论(六):GraphRAG(基于知识图谱的 RAG),从相似文本走向实体关系
人工智能·后端·设计模式