What is the js template pattern
This article focuses on "what is the js template pattern", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the js template pattern"!
What is template mode?
The template pattern is an abstract parent class that defines related methods that subclasses need to override. These methods, however, are still called through parent class methods. According to the description, the idea of "template" is embodied in the interface method defined by the parent class. In addition, calls to subclass methods are also controlled by the parent class.
Application scenario
Some system architecture or algorithm framework, by the "BOSS" to write abstract methods, specific implementation, to the "boys" to achieve. And definitely not using the "boys" method, or watching "BOSS" mood. It's not a very appropriate metaphor, huh?
ES6 implementation
Animal is an abstract class, and Dog and Cat implement the eat () and sleep () methods, respectively. Dog or Cat instances can call eat () and sleep () through the live () method.
Note: Cat and Dog instances are automatically added with the live () method. The purpose of not exposing live () is to prevent live () from being overwritten by the subclass and to guarantee control of the parent class.
Class Animal {
Constructor () {
/ / this points to the instance
This.live = () = > {
This.eat ()
This.sleep ()
}
}
Eat () {
Throw new Error (template class methods must be overridden)
}
Sleep () {
Throw new Error (template class methods must be overridden)
}
}
Class Dog extends Animal {
Constructor (. Args) {
Super (. Args)
}
Eat () {
Console.log ("dogs eat food")
}
Sleep () {
Console.log ("Dog sleeps")
}
}
Class Cat extends Animal {
Constructor (. Args) {
Super (. Args)
}
Eat () {
Console.log ("Cats eat food")
}
Sleep () {
Console.log ("cat sleeps")
}
}
/ * the following is the test code * /
/ / at this point, the this in Animal points to dog
Let dog = new Dog ()
Dog.live ()
/ / at this point, the this in Animal points to cat
Let cat = new Cat ()
Cat.live ()
At this point, I believe you have a deeper understanding of "what is the js template pattern". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!