Factory with composition
suggest change‘Prefer composition over inheritance’ is an important and popular programming principle, used to assign behaviors to objects, as opposed to inheriting many often unneeded behaviors.
Behaviour factories
const speaker = function (state) {
const noise = state.noise || 'grunt';
return {
speak: function () {
console.log(state.name + ' says ' + noise);
}
};
};
const mover = function (state) {
return {
moveSlowly: function () {
console.log(state.name + ' is moving slowly');
},
moveQuickly: function () {
console.log(state.name + ' is moving quickly');
}
};
};
Object factories
const person = function (name, age) {
const state = {
name: name,
age: age,
noise: 'Hello'
};
return Object.assign( // Merge our 'behaviour' objects
{},
speaker(state),
mover(state)
);
};
const rabbit = function (name, colour) {
const state = {
name: name,
colour: colour
};
return Object.assign(
{},
mover(state)
);
};
Usage
const fred = person('Fred', 42);
fred.speak(); // outputs: Fred says Hello
fred.moveSlowly(); // outputs: Fred is moving slowly
const snowy = rabbit('Snowy', 'white');
snowy.moveSlowly(); // outputs: Snowy is moving slowly
snowy.moveQuickly(); // outputs: Snowy is moving quickly
snowy.speak(); // ERROR: snowy.speak is not a function
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents