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

相关推荐
geovindu1 小时前
go: Chain of Responsibility Pattern
开发语言·设计模式·golang·责任链模式
陈天伟教授7 小时前
GPT Image 2-勾股定理
大数据·数据库·人工智能·gpt
数字游民95279 小时前
gpt image 2怎么用?附超全提示词案例库
人工智能·gpt·ai·opc·waytoopc·数字游民9527
guokai.wu10 小时前
GPT-5.5 简要介绍(免费使用方法)
gpt
陈天伟教授11 小时前
GPT Image 2-城市海报
开发语言·人工智能·gpt·神经网络
原来是猿11 小时前
线程安全的单例模式
linux·服务器·开发语言·单例模式·策略模式
陈天伟教授11 小时前
GPT Image 2-天府成都
人工智能·gpt·安全
JavaEdge.13 小时前
GPT-5.5 发布:一种面向真实工作的全新智能形态
gpt
熊文豪13 小时前
拆解 awesome-gpt-image-2-prompts:一份 GPT-Image-2 的社区实战提示词样本
gpt·dreamweaver·gpt-image-2
Resistance丶未来14 小时前
DeepSeek-V4 新手快速上手指南
数据结构·python·gpt·算法·机器学习·claude·claude 4.6