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

相关推荐
是2的10次方啊8 小时前
设计模式与生活⑰:空腹体检,单子领着人走
设计模式
进击的荆棘1 天前
Linux系统——线程同步与互斥
linux·运维·服务器·策略模式·同步·互斥·posix
是2的10次方啊1 天前
设计模式与生活⑯:天冷了,出门这身得一层层配
设计模式
心若自由何处是束缚2 天前
适配器模式:从原理到实战的完整指南
设计模式·适配器模式
是2的10次方啊2 天前
设计模式与生活⑮:看到哪儿了,得有个地方替你记着
设计模式
謓泽2 天前
【插件】用写网页的方式做视频?HyperFrames 让我重新理解了“做视频“这件事!
gpt·ai·大模型·音视频·媒体·claude·视频
2601_967979123 天前
设计模式 - 访问者模式
设计模式·访问者模式·应用场景·对象结构·操作分离
是2的10次方啊3 天前
设计模式与生活⑭:一栋楼,共用一份热
设计模式
一缕82年的清风4 天前
7 美元芯片如何给 AI 挂上“物理手眼”?从 AirPlay 视讯流到 USB HID 物理注入的真实硬件黑客流
gpt·claude
是2的10次方啊4 天前
设计模式与生活⑬:你坐几号线,谁来运营是另一回事
设计模式