首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mixins与Strategies

Mixins与Strategies
EN

Stack Overflow用户
提问于 2015-05-20 04:02:34
回答 1查看 565关注 0票数 3

我正在努力理解java中的混合和策略之间的区别。他们是否都以不同的方式做同样的事情?有人能帮我把这个弄清楚吗?

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2015-07-28 11:38:53

当您想要获取一个对象并“混合”新功能时,可以使用Mixins,因此在Javascript中,您通常使用新方法扩展对象的原型。

使用策略模式,您的对象由一个“策略”对象组成,该对象可以与遵循相同接口(相同的方法签名)的其他策略对象交换。每个策略对象包含不同的算法,并且最终由业务逻辑的复合对象使用的算法由换入的策略对象决定。

所以基本上,这是一个如何指定特定对象的功能的问题。通过: 1.扩展(继承自一个Mixin对象,或多个Mixin对象)。2.可切换策略对象的组成。

在Mixin和Strategy模式中,您都摆脱了子类化,这通常会带来更灵活的代码。

下面是策略模式在JSFiddle上的一个实现:https://jsfiddle.net/richjava/ot21bLje/

代码语言:javascript
复制
  "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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30335086

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档