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

相关推荐
明洞日记14 分钟前
【设计模式手册011】享元模式 - 共享细粒度对象的高效之道
java·设计模式·享元模式
帅中的小灰灰34 分钟前
C++编程观察者设计模式
数据库·c++·设计模式
阿波罗尼亚2 小时前
Head First设计模式(六) 设计原则 命令模式
设计模式·命令模式
大佬,救命!!!4 小时前
C++函数式策略模式代码练习
开发语言·c++·学习笔记·学习方法·策略模式·迭代加深·多文件编译
极客BIM工作室4 小时前
从Transformer的Encoder与Decoder,到BERT和GPT的独立王国
gpt·bert·transformer
canonical_entropy4 小时前
模型驱动架构的数学内核:统一生成与演化的 Y = F(X) ⊕ Delta 不变式
数学·设计模式·架构
小毛驴8504 小时前
软件设计模式-代理模式
设计模式·系统安全·代理模式
雨中飘荡的记忆21 小时前
工厂模式详解
设计模式
Charles_go1 天前
C#42、什么是建造者设计模式
设计模式
烤麻辣烫1 天前
23种设计模式(新手)-3接口隔离原则
java·开发语言·学习·设计模式·intellij-idea