混合和策略在Java中的区别

3

我很难理解Java中Mixin和Strategy的区别。它们是否以不同的方式执行相同的操作?有人能帮我澄清一下吗?

谢谢!

1个回答

4
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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接