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

相关推荐
OpenCSG9 小时前
GPT-5.6 深夜正式上线:下一代模型能力升级,AI Agent 进入深度协作时代
人工智能·gpt
第一个传播学15 小时前
忍者龙剑传4豪华版下载及其玩法解析
设计模式
To_OC1 天前
还在追顶配模型?GPT 5.6 已经把玩法彻底改了
人工智能·gpt·llm
Days20501 天前
帮我在书本上画出了回忆中的学校-提示词
人工智能·gpt·ai作画·gpt-image
就是一顿骚操作1 天前
GPT-2 from scratch with torch:用 torch 从零实现 GPT-2
人工智能·gpt·transformer·论文解读·gpt-2
sugar__salt1 天前
Benchmark 与 GPT 5.6:大模型评测体系与 AI 工作方式的范式转移
人工智能·gpt
大鱼>1 天前
Whisper+GPT-SoVITS:语音识别到音色克隆的全链路实战
gpt·whisper·语音识别
第一个传播学2 天前
赛博朋克2077修改器下载及其用法
设计模式
萧青山2 天前
2026国标合规:Agent Loop合规设计模式的6种循环架构(GB/Z 185.6+Python)
python·设计模式·agent loop·gb/z 185·国标合规
库拉大叔2 天前
在盈彩AI使用GPT-Image-2:从入门到精通的完整指南
人工智能·gpt