示例参考 - ES5
<script>
function Order() {
// 未优惠前的价格
this.originalPrice = 10;
// 支付方式
this.paidBy = null;
}
/**
* 设置支付方式
* @param paidBy 策略实例
*/
Order.prototype.setPaidBy = function (paidBy) {
this.paidBy = paidBy;
}
/**
* 计算最终付款价格
* @return {number}
*/
Order.prototype.calc = function () {
return this.paidBy.calc(this.originalPrice);
}
/**
* 学生卡策略
* @constructor
*/
function StudentCard() {}
StudentCard.prototype.calc = function (total) {
return total;
}
/**
* 教师卡策略
* @constructor
*/
function TeacherCard() {}
TeacherCard.prototype.calc = function (total) {
return total * .9;
}
/**
* 现金策略
* @constructor
*/
function Cash() {}
Cash.prototype.calc = function (total) {
return total * 1.1;
}
var order = new Order();
order.setPaidBy(new Cash());
console.log(order.calc())
</script>
示例参考 - ES6
<script>
class Order {
constructor() {
// 未优惠前的价格
this.originalPrice = 10;
// 支付方式
this.paidBy = null;
}
/**
* 设置支付方式
* @param paidBy 策略实例
*/
setPaidBy(paidBy) {
this.paidBy = paidBy;
}
/**
* 计算最终付款价格
* @return {number}
*/
calc() {
return this.paidBy.calc(this.originalPrice);
}
}
/**
* 学生卡策略
* @constructor
*/
class StudentCard {
calc(total) {
return total;
}
}
/**
* 教师卡策略
* @constructor
*/
class TeacherCard {
calc(total) {
return total * .9;
}
}
/**
* 现金策略
* @constructor
*/
class Cash {
calc(total) {
return total * 1.1;
}
}
var order = new Order();
order.setPaidBy(new Cash());
console.log(order.calc())
</script>
登录后评论