策略模式核心是分离算法定义与使用,JavaScript中可通过函数对象(如discountStrategies)或类(如FixedDiscountStrategy)实现,结合工厂函数动态选择策略,确保纯度、可测性与低耦合。

策略模式的核心是把算法的定义和使用分开,让不同算法可以互相替换而不影响调用方。在 JavaScript 中,这通常通过函数或对象封装行为、用统一接口调用实现。
把每种算法写成独立函数,挂载到一个策略对象上,调用时根据条件选择对应函数:
const discountStrategies = {
'vip': (price) => price * 0.8,
'promo': (price) => Math.max(price - 50, 0),
'newUser': (price) => price * 0.95,
'default': (price) => price
};
<p>function calculatePrice(price, strategyKey) {
const strategy = discountStrategies[strategyKey] || discountStrategies.default;
return strategy(price);
}</p><p>calculatePrice(100, 'vip'); // 80
calculatePrice(100, 'promo'); // 50
当策略需要维护内部状态(如计数器、缓存)或依赖外部服务时,用类更合适:
class FixedDiscountStrategy {
constructor(fixedAmount) {
this.fixedAmount = fixedAmount;
}
execute(price) {
return Math.max(price - this.fixedAmount, 0);
}
}
<p>class PercentageDiscountStrategy {
constructor(rate) {
this.rate = rate;
}
execute(price) {
return price * (1 - this.rate);
}
}</p><p>// 使用时切换策略实例
let currentStrategy = new FixedDiscountStrategy(30);
console.log(currentStrategy.execute(100)); // 70</p><p>currentStrategy = new PercentageDiscountStrategy(0.2);
console.log(currentStrategy.execute(100)); // 80
真实业务中,策略选择常依赖用户属性、环境或规则引擎。可以用简单工厂封装判断逻辑:
立即学习“Java免费学习笔记(深入)”;
function createDiscountStrategy(user, order) {
if (user.level === 'vip' && order.total > 500) {
return new PercentageDiscountStrategy(0.25);
}
if (user.isNew && order.items.length > 0) {
return new PercentageDiscountStrategy(0.1);
}
return new FixedDiscountStrategy(10);
}
<p>const strategy = createDiscountStrategy(currentUser, currentOrder);
const finalPrice = strategy.execute(currentOrder.total);
策略函数或类应尽量无副作用、不依赖全局状态:
不复杂但容易忽略。
以上就是Javascript如何实现策略模式_如何灵活替换算法?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号