Design Patterns
github.com/otaviopace
Otávio Pace
O que são?
São soluções estabelecidas para problemas recorrentes do desenvolvimento de software
Um exemplo
const penguin = new Animal(
// Chordata Phylum
new Phylum({
Subkingdom: 'Eumetazoa',
Clade: ['Bilateria', 'Nephrozoa'],
Superphylum: 'Deuterostomia',
}),
// Aves Class
new Class({
Clade: 'Ornithurae',
}),
// Sphenisciformes Order
new Order('Sphenisciformes'),
// Spheniscidae Family
new Family('Spheniscidae'),
// Species
'Eudyptula'
)
const penguin = new PenguinFactory('Eudyptula')
Mas de onde eles vieram?
Christopher Alexander
![](https://s3.amazonaws.com/media-p.slid.es/uploads/852577/images/5165211/ChristopherAlexander2012.jpg)
Kent Beck
![](https://s3.amazonaws.com/media-p.slid.es/uploads/852577/images/5165218/230px-Ward_Cunningham_-_Commons-1.jpg)
Ward Cunningham
![](https://s3.amazonaws.com/media-p.slid.es/uploads/852577/images/5196118/kent_beck2.jpg)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/852577/images/5165225/design_patterns_book.jpg)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/852577/images/5165279/gang_of_four.jpeg)
Gang of Four
E eles ainda são aplicáveis?
Sim!
As vezes não sabemos nem por onde começar ao tentar resolver um problema
Exemplo de memorização
class Calculator {
doExpensiveCalculation () {
return 1 + 1
}
}
const calculator = new Calculator()
calculator.doExpensiveCalculation() // calculates 2
calculator.doExpensiveCalculation() // calculates 2
class Calculator {
doExpensiveCalculation () {
return 1 + 1
}
}
class CalculatorDecorator {
constructor () {
this.hasCalculated = false
this.realCalculator = new Calculator()
}
doExpensiveCalculation () {
if (!this.hasCalculated) {
this.result = this.realCalculator
.doExpensiveCalculation()
this.hasCalculated = true
return this.result
}
return this.result
}
}
const calculator = new Calculator()
calculator.doExpensiveCalculation() // calculates 2
calculator.doExpensiveCalculation() // calculates 2
const decorator = new CalculatorDecorator()
decorator.doExpensiveCalculation() // calculates 2
decorator.doExpensiveCalculation() // gets cache of 2
Contribuir a outros projetos
![](https://s3.amazonaws.com/media-p.slid.es/uploads/852577/images/5196131/good_rails.png)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/852577/images/5196139/good_v8.png)
Fácil entendimento de código
![](https://s3.amazonaws.com/media-p.slid.es/uploads/852577/images/5165247/blur_code.png)
Cuidado!
![](https://s3.amazonaws.com/media-p.slid.es/uploads/852577/images/5147470/warning_emoji.png)
Se seu time não sabe design patterns, isso pode dificultar a legibilidade
Não tente utilizar um pattern para resolver um problema que ele não foi feito para resolver
O abuso dos patterns pode complicar mais o código
![](https://s3.amazonaws.com/media-p.slid.es/uploads/852577/images/5150169/factory.png)
Strategy Pattern!
class Potato {
constructor () {
this.foodName = 'potato'
}
setCookStrategy (cookStrategy) {
this.cookStrategy = cookStrategy
}
cook () {
this.cookStrategy.cook(this.foodName)
}
}
class Boiled {
cook (foodName) {
console.log(`Boiling ${foodName}!`)
}
}
class Fried {
cook (foodName) {
console.log(`Frying ${foodName}!`)
}
}
const potato = new Potato()
potato.setCookStrategy(new Boiled())
potato.cook() // Boiling potato!
potato.setCookStrategy(new Fried())
potato.cook() // Frying potato!
Chain of Responsibility Pattern!
class Padawan {
constructor () {
this.master = new Knight()
}
fight (monster) {
if (monster.strength > 10) {
console.log('I am too weak for this :(')
return this.callMasterToFight(monster)
}
this.punch()
}
callMasterToFight (monster) {
this.master.fight(monster)
}
punch () {
console.log('A weak padawan punch!')
}
}
class Knight {
constructor () {
this.master = new Master()
}
fight (monster) {
if (monster.strength > 100) {
console.log('I am too weak for this :(')
return this.callMasterToFight(monster)
}
this.swingLightSaber()
}
callMasterToFight (monster) {
this.master.fight(monster)
}
swingLightSaber () {
console.log('Schvrmmmmmmm!')
}
}
class Master {
fight (monster) {
this.useTheForce()
}
callMasterToFight (monster) {
throw new Error('I am the ultimate master!')
}
useTheForce () {
console.log('You\'re finished!')
}
}
const weakMonster = { strength: 7 }
const padawan = new Padawan()
padawan.fight(weakMonster)
// Padawan: A weak padawan punch!
const averageMonster = { strength: 60 }
padawan.fight(averageMonster)
// Padawan: I am too weak for this :(
// Knight: Schvrmmmmmmm!
const ultraMonster = { strength: 560 }
padawan.fight(ultraMonster)
// Padawan: I am too weak for this :(
// Knight: I am too weak for this :(
// Master: You're finished!
📚Referências
https://github.com/otaviopace/design-patterns
![](https://emojipedia-us.s3.amazonaws.com/thumbs/160/google/119/gear_2699.png)
🏜️
Obrigado!
![](https://emojipedia-us.s3.amazonaws.com/thumbs/160/whatsapp/116/heavy-black-heart_2764.png)
Design Patterns
By otaviopace
Design Patterns
- 906