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

相关推荐
致Great41 分钟前
Nano Banana提示语精选
人工智能·gpt·chatgpt·开源·agent
漫长的~以后3 小时前
GPT-5.2深度拆解:多档位自适应架构如何重塑AI推理效率
人工智能·gpt·架构
fakerth4 小时前
【OpenHarmony】设计模式模块详解
c++·单例模式·设计模式·openharmony
alibli6 小时前
一文学会设计模式之创建型模式及最佳实现
c++·设计模式
1024肥宅8 小时前
前端常用模式:提升代码质量的四大核心模式
前端·javascript·设计模式
川川菜鸟12 小时前
GPT-5.2 已同步国内上线:全面超越 Claude、Gemini 3
gpt
热点速递12 小时前
谷歌深夜开源“Gemini Deep Research Agent”,实现SOTA并以1/10成本挑战!GPT‑5 Pro!
gpt·业界资讯
GMICLOUD12 小时前
GMI Cloud@AI周报|GPT 5.2 重磅发布;智谱AI GLM-4.6V开源;
人工智能·gpt·业界资讯
郝学胜-神的一滴12 小时前
设计模式依赖于多态特性
java·开发语言·c++·python·程序人生·设计模式·软件工程
哪 吒12 小时前
OpenAI发布GPT 5.2,全面反击Gemini 3 Pro,国内直接使用
gpt·ai·chatgpt·大模型·gemini·gpt5.2