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 负责管理策略的创建和选择逻辑,这使得代码更简洁且易于维护。

相关推荐
Nayxxu4 小时前
Gemini、Claude、GPT 多模型网关最小实现方案
人工智能·gpt
夜雪闻竹5 小时前
Codex CLI / Trae / Copilot 数据源接入
gpt·copilot·ai-native
geovindu6 小时前
go: Read-Write Lock Pattern
开发语言·后端·设计模式·golang·读写锁模式
Mr.朱鹏8 小时前
9-检索增强生成RAG详解
python·gpt·langchain·大模型·llm·rag
行走的陀螺仪9 小时前
[特殊字符] JavaScript 设计模式完全指南:从入门到精通(含20种模式)
开发语言·javascript·设计模式
小陶来咯9 小时前
AI Agent 设计模式:ReAct 深度解析
人工智能·react.js·设计模式
代码对我眨眼睛9 小时前
Mac 如何单独修改鼠标滚动方向,而不影响触控板
macos·计算机外设·策略模式
多加点辣也没关系11 小时前
设计模式-责任链模式
设计模式·责任链模式
jiushiaifenxiang11 小时前
Parallels Desktop for Mac 26.3.2 (57398)中文版新功能介绍
macos·策略模式
多加点辣也没关系11 小时前
设计模式-命令模式
设计模式·命令模式