I'm struggling to understand the differences between mixins and strategies in java. Do they both do the same thing in different ways? could anybody clear this up for me?
Thanks!
Mixins are used when you want to take an object and “mix in” new functionality, so in Javascript you’re generally extending the object’s prototype with new methods.
With the Strategy pattern, your object is composed of a “strategy” object that can be swapped out for other strategy objects that adhere to the same interface (same method signatures). Each strategy object contains a different algorithm, and the algorithm that is ultimately used by the composite object for business logic is determined by whichever strategy object has been swapped in.
So basically, it’s a matter of how you specify the functionality of a particular object. By either: 1. Extension (inheriting from a Mixin object, or multiple Mixin objects). 2. Composition of swappable Strategy objects.
In both Mixin and Strategy patterns, you’re getting away from subclassing and this often results in more flexible code.
Here is an implementation of the Strategy pattern on 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();
And an explanation from Rob Dodson: http://robdodson.me/javascript-design-patterns-strategy/
Addy Osmani explains the Mixin pattern well here: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#mixinpatternjavascript
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With