我正在努力理解 Java 中的 mixins 和策略之间的区别。他们都以不同的方式做同样的事情吗?谁能帮我解决这个问题?
谢谢!
最佳答案
当你想获取一个对象并“混合”新功能时,会使用 Mixins,因此在 Javascript 中,你通常会使用新方法扩展对象的原型(prototype)。
使用策略模式,您的对象由一个“策略”对象组成,该对象可以换成其他遵循相同接口(interface)(相同方法签名)的策略对象。每个策略对象包含不同的算法,复合对象最终用于业务逻辑的算法由换入的策略对象决定。
所以基本上,这就是您如何指定特定对象的功能的问题。通过: 1.扩展(继承自一个Mixin对象,或者多个Mixin对象)。 2. 可交换策略对象的组合。
在 Mixin 和 Strategy 模式中,您正在摆脱子类化,这通常会导致更灵活的代码。
这是 JSFiddle 上策略模式的实现:https://jsfiddle.net/richjava/ot21bLje/
"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
关于java - Mixins 与 Strategies Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30335086/