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

相关推荐
Yeniden4 小时前
【设计模式】# 外观模式(Facade)大白话讲解!
java·设计模式·外观模式
Yeniden4 小时前
【设计模式】 组合模式(Composite)大白话讲解
java·设计模式·组合模式
DisonTangor6 小时前
OpenAI开源gpt-oss-safeguard-120b和gpt-oss-safeguard-20b
人工智能·gpt·语言模型·开源·aigc
Baihai IDP6 小时前
对 GPT 5 模型路由机制的深度解析
人工智能·gpt·ai·大模型·llms
七宝大爷6 小时前
从 “你好 Siri” 到 “你好 GPT”:语言模型如何改变对话?
人工智能·gpt·语言模型
山山而川 潺潺如镜8 小时前
chatgpt崩溃了,gpt怎么了
gpt
R.lin12 小时前
Java支付对接策略模式详细设计
java·架构·策略模式
Damon小智12 小时前
鸿蒙元服务深度实践:跨端唤醒与状态共享的设计模式
华为·设计模式·harmonyos
shaominjin12312 小时前
单例模式:设计模式中的“独一无二“之道
android·单例模式·设计模式
欠你一个bug17 小时前
Java设计模式应用--装饰器模式
java·设计模式·装饰器模式