我很难理解Java中Mixin和Strategy的区别。它们是否以不同的方式执行相同的操作?有人能帮我澄清一下吗?
谢谢!
我很难理解Java中Mixin和Strategy的区别。它们是否以不同的方式执行相同的操作?有人能帮我澄清一下吗?
谢谢!
"use strict";
function Customer(billingStrategy) {
//list for storing drinks
this.drinks = [];
this.billingStrategy = billingStrategy;
}
Customer.prototype.add = function(price, quantity) {
this.drinks.push(this.billingStrategy.getPrice(price * quantity));
};
Customer.prototype.printBill = function() {
var sum = 0;
for (var i = 0; i < this.drinks.length; i++) {
sum += this.drinks[i];
}
console.log("Total due: " + sum);
this.drinks = [];
};
// Define our billing strategy objects
var billingStrategies = {
normal: {
getPrice: function(rawPrice) {
return rawPrice;
}
},
happyHour: {
getPrice: function(rawPrice) {
return rawPrice * 0.5;
}
}
};
console.log("****Customer 1****");
var customer1 = new Customer(billingStrategies.normal);
customer1.add(1.0, 1);
customer1.billingStrategy = billingStrategies.happyHour;
customer1.add(1.0, 2);
customer1.printBill();
// New Customer
console.log("****Customer 2****");
var customer2 = new Customer(billingStrategies.happyHour);
customer2.add(0.8, 1);
// The Customer pays
customer2.printBill();
// End Happy Hour
customer2.billingStrategy = billingStrategies.normal;
customer2.add(1.3, 2);
customer2.add(2.5, 1);
customer2.printBill();
以下是Rob Dodson的解释:http://robdodson.me/javascript-design-patterns-strategy/
Addy Osmani在这里很好地解释了Mixin模式:http://addyosmani.com/resources/essentialjsdesignpatterns/book/#mixinpatternjavascript