Skip to content

Instantly share code, notes, and snippets.

@miksansegundo
Last active November 24, 2015 18:12
Show Gist options
  • Save miksansegundo/0ca0f133876887df3410 to your computer and use it in GitHub Desktop.
Save miksansegundo/0ca0f133876887df3410 to your computer and use it in GitHub Desktop.
// Glass Factory
function glass(state) {
var glasses = 6
state.glassPosition = 'up'
return {
glass: {
clean: function () {
state.cleaned = true
console.info('Glass cleaned')
},
up: function () {
state.glassPosition = 'up'
console.info('Glass up')
},
down: function () {
state.glassPosition = 'down'
console.info('Glass down')
},
add: function () {
glasses += 1
console.info('Glass added')
},
get: function () {
console.info('Total glasses: ', glasses)
}
}
}
}
// Engine Factory
function engine(state) {
return {
engine: {
start: function () {
state.started = true
console.info('Engine started')
},
stop: function () {
state.started = false
console.info('Engine stopped')
}
}
}
}
// Car compositor
function car() {
var state = {
started: false,
cleaned: false,
glassPosition: null
}
return Object.assign(
{},
engine(state),
glass(state)
)
}
// Usage
var myCar = car();
myCar.engine.start();
myCar.glass.down();
// This is the easy way for Composition Factories
// Factories are closures that returns objects with public methods
// But they save an internal state with vars & private methods
Object.assign({}, obj1, obj2) // Clona o fusiona objetos
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment