I'm going through the Head First Design Patterns book and I want to check whether I'm understanding some aspects of the first chapter. Does the code below program correctly to interfaces, encapsulate changeable behavior, and employ composition in a reasonable manner?
// trying to enforce some design pattern habits
// create a duck, that prints a line to the page as text
class DuckAbilities {
constructor() {
this.flying = new FlyBehavior()
}
addToPage() {
this.statement = document.createElement("p")
this.statement.innerHTML=this.flying.fly()
document.body.append(this.statement)
}
}
//interface for behaviors
class FlyBehavior {
fly() {
null
}
}
class DoesFly{
fly() {
return "I'm flying"
}
}
class DoesNotFly {
fly() {
return "not flying"
}
}
class Mallard {
constructor() {
this.abilities = new DuckAbilities()
this.abilities.flying = new DoesFly()
}
}
class Rubber{
constructor() {
this.abilities = new DuckAbilities()
this.abilities.flying = new DoesNotFly()
}
}
window.onload = ()=> {
let mallard = new Mallard()
mallard.abilities.addToPage()
let rubber = new Rubber()
rubber.abilities.addToPage()
}
Interfaceimplementation. Due to JS's nature proper interface-y code will not look like the examples inHead First.Google for JS specific examples - which will be different depending on the version of JS you use. \$\endgroup\$Head Firstbook and forget JS for its sake - I like theHead Firstseries a lot & have several of their titles, includingDesign Patterns. \$\endgroup\$