专业做相册书的网站,wordpress 更改首页,网站宣传推广方案,php网站伪静态概述
策略模式
例子
你可以创建一个策略工厂#xff08;Strategy Factory#xff09;来根据传入的 orgId 动态地选择合适的策略。以下是实现示例#xff1a;
首先#xff0c;定义策略接口和具体策略类#xff1a;
public interface CardPathStrategy {String generat…概述
策略模式
例子
你可以创建一个策略工厂Strategy Factory来根据传入的 orgId 动态地选择合适的策略。以下是实现示例
首先定义策略接口和具体策略类
public interface CardPathStrategy {String generatePath();
}public class OrganizationAStrategy implements CardPathStrategy {Overridepublic String generatePath() {return path/for/organizationA;}
}public class OrganizationBStrategy implements CardPathStrategy {Overridepublic String generatePath() {return path/for/organizationB;}
}创建一个策略工厂 CardPathStrategyFactory 来根据 orgId 返回相应的策略
import java.util.HashMap;
import java.util.Map;public class CardPathStrategyFactory {private static final MapString, 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);}
}在你的业务逻辑中使用策略工厂
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/organizationAorgId orgB; // 更改组织IDstrategy 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 负责管理策略的创建和选择逻辑这使得代码更简洁且易于维护。