GPT带我学-设计模式13-策略模式

概述

策略模式

例子

你可以创建一个策略工厂(Strategy Factory)来根据传入的 orgId 动态地选择合适的策略。以下是实现示例:

  1. 首先,定义策略接口和具体策略类:
java 复制代码
public interface CardPathStrategy {
    String generatePath();
}

public class OrganizationAStrategy implements CardPathStrategy {
    @Override
    public String generatePath() {
        return "path/for/organizationA";
    }
}

public class OrganizationBStrategy implements CardPathStrategy {
    @Override
    public String generatePath() {
        return "path/for/organizationB";
    }
}
  1. 创建一个策略工厂 CardPathStrategyFactory 来根据 orgId 返回相应的策略:
java 复制代码
import java.util.HashMap;
import java.util.Map;

public class CardPathStrategyFactory {
    private static final Map<String, CardPathStrategy> strategies = new HashMap<>();

    static {
        strategies.put("orgA", new OrganizationAStrategy());
        strategies.put("orgB", new OrganizationBStrategy());
        // 添加更多策略
    }

    public static CardPathStrategy getStrategy(String orgId) {
        return strategies.get(orgId);
    }
}
  1. 在你的业务逻辑中使用策略工厂:
java 复制代码
public class CardPathGenerator {
    public static void main(String[] args) {
        String orgId = "orgA";  // 这个可以是传入的参数

        CardPathStrategy strategy = CardPathStrategyFactory.getStrategy(orgId);
        if (strategy == null) {
            throw new IllegalArgumentException("No strategy found for orgId: " + orgId);
        }

        CardPathContext context = new CardPathContext(strategy);
        System.out.println(context.generateCardPath());  // 输出:path/for/organizationA

        orgId = "orgB";  // 更改组织ID
        strategy = CardPathStrategyFactory.getStrategy(orgId);
        if (strategy == null) {
            throw new IllegalArgumentException("No strategy found for orgId: " + orgId);
        }

        context.setStrategy(strategy);
        System.out.println(context.generateCardPath());  // 输出:path/for/organizationB
    }
}

通过这种方式,你可以根据传入的 orgId 动态地选择不同的策略。工厂类 CardPathStrategyFactory 负责管理策略的创建和选择逻辑,这使得代码更简洁且易于维护。

相关推荐
han_42 分钟前
JavaScript设计模式(十):模板方法模式实现与应用
前端·javascript·设计模式
Ztop1 小时前
一文说清ChatGPT Pro 5x 和 20x 区别,以及国内如何升级ChatGPT Pro 最新教程
人工智能·gpt·chatgpt
楼田莉子2 小时前
仿muduo库的高并发服务器——项目基本认识及其相关概念
服务器·数据结构·c++·学习·设计模式
dozenyaoyida2 小时前
嵌入式设计模式之策略模式(2)
经验分享·设计模式·策略模式
witAI2 小时前
gpt写小说工具2025推荐,助力高效创作小说
人工智能·python·gpt
Wild API3 小时前
Claude、GPT、Gemini 场景对比表
人工智能·gpt·深度学习
Cosolar15 小时前
Nanobot 深度解析:超轻量级通用 AI Agent 运行时的架构设计与实战指南
gpt·llm·ai编程
Ztopcloud极拓云视角1 天前
GPT-6 & DeepSeek V4 双雄临近:企业多模型路由网关实战指南
人工智能·gpt·deepseek·gpt-6
汤姆yu1 天前
GPT-6核心能力解析及与现有主流大模型对比
gpt·大模型·gpt6