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')
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
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!
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!
🏜️