What is polymorphism
Polymorphism literally means multiple states. The same operation on different objects can have different interpretations and different execution results. For example, I have a cat and a dog, I send the same instruction to them “is called a”, cats meow meow meow, and dogs can auf, so that they call the is the same operation, and sound is different results. The pseudo-code implementation looks like this:
function getVoice(animals) {
if(animals instanceof Cat){
console.log('meow ~');
}
if(animals instanceof Dog){
console.log('wang ~'); }}class Cat {}
class Dog {}
getVoice(new Cat()); // 'meow ~'
getVoice(new Dog()); // '/'
Copy the code
So what if we want to add an animal? One more judgment? So then I have to change getVoice every time I want to add an animal call? Isn’t it a bit tedious?
So we have to figure out how to solve this problem ~
Object polymorphism
In fact, the most fundamental function of polymorphism is to eliminate conditional branch statements by transforming procedural conditional statements into object polymorphism.
In general terms, it’s separating what from who does it and how, and it’s separating what doesn’t change from what can change.
The original example can be broken down like this:
Things that don’t change are: animals make calls things that might change are: what animals make what calls
Then we can distribute the “animal cry” action to each class (encapsulate each class) and call the “call” action in the getVoice function that produces the call.
This example can be modified to look like this
function getVoice (animals) {
if (animals.sound instanceof Function) {
// Determine if there is animal.sound and the property is a functionanimals.sound(); }}class Cat {
sound () {
console.log('meow ~'); }}class Dog {
sound () {
console.log('wang ~');
}
}
getVoice(new Cat()); // 'meow ~'
getVoice(new Dog()); // '/'
Copy the code
Practical applications of polymorphism
Polymorphism is widely used in design patterns, such as composition/strategy patterns and so on. ~ ~
Although we don’t use it much in development, polymorphism is useful once we get into some design patterns