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

相关推荐
绅士玖10 小时前
JavaScript 设计模式之单例模式🚀
前端·javascript·设计模式
永卿00111 小时前
设计模式-门面模式
设计模式
凤山老林11 小时前
Spring Boot中的中介者模式:终结对象交互的“蜘蛛网”困境
java·spring boot·后端·设计模式·中介者模式
找了一圈尾巴13 小时前
设计模式(结构型)-适配器模式
设计模式·适配器模式
vvilkim13 小时前
单例模式详解:确保一个类只有一个实例
单例模式·设计模式
CodeWithMe13 小时前
【读书笔记】《C++ Software Design》第六章深入剖析 Adapter、Observer 和 CRTP 模式
c++·设计模式
归于尽14 小时前
从本地存储封装读懂单例模式:原来这就是设计模式的魅力
前端·javascript·设计模式
海底火旺14 小时前
单例模式的实现
前端·javascript·设计模式
3Katrina14 小时前
《JavaScript单例模式详解:从原理到实践》
前端·javascript·设计模式
Code季风15 小时前
测试驱动开发(TDD)实战:在 Spring 框架实现中践行 “红 - 绿 - 重构“ 循环
java·驱动开发·后端·spring·设计模式·springboot·tdd