【问题标题】:Mixins versus Strategies JavaMixins 与策略 Java
【发布时间】:2015-07-31 20:09:06
【问题描述】:

我很难理解 java 中 mixins 和策略之间的区别。他们都以不同的方式做同样的事情吗?谁能帮我解决这个问题?

谢谢!

【问题讨论】:

    标签: java mixins strategy-pattern


    【解决方案1】:

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

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

    所以基本上,这是一个你如何指定特定对象的功能的问题。通过以下任一方式: 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      • 2014-11-01
      • 1970-01-01
      相关资源
      最近更新 更多