GPT带我学-设计模式13-策略模式

概述

策略模式

例子

你可以创建一个策略工厂(Strategy Factory)来根据传入的 orgId 动态地选择合适的策略。以下是实现示例:

  1. 首先,定义策略接口和具体策略类:
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 返回相应的策略:
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. 在你的业务逻辑中使用策略工厂:
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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值