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

Kent Beck

Ward Cunningham

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

Fácil entendimento de código

Cuidado!

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

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

🏜️

Obrigado!

Design Patterns

By otaviopace

Design Patterns

  • 939