js面向对象系列五之多态函数
多态字面意思多种状态,指的是不一样的对象按照统一接口执行时,产生多种不一样的结果即同一个实现接口,使用不一样的实例而执行不一样的操做。prototype
按照网上看来的一个例子;主人发出一个"叫"的命令,狗发出汪汪的叫声,猫发出喵喵的叫声code
常规非多态代码对象
//非多态代码 function makeSound(animal) { if(animal instanceof Dog) { console.log("汪汪汪") } else if (animal instanceof Cat) { console.log("喵喵") } } function Dog() {} function Cat() {} makeSound(new Dog()) makeSound(new Cat())
// 多态代码 function makeSound2(animal) { animal.sound() } function Dog2(){} Dog2.prototype.sound = function() { console.log("汪汪汪") } function Cat2(){} Cat2.prototype.sound =function() { console.log("喵喵喵") } makeSound2(new Dog2()) makeSound2(new Cat2())
比较而言,多态代码比非多态代码要臃肿,可是多态代码比非多态代码要好扩展和维护接口
为什么这么说,我么若是要添加了个狼的叫声,若是是非多态代码io
//非多态代码 function makeSound(animal) { if(animal instanceof Dog) { console.log("汪汪汪") } else if (animal instanceof Cat) { console.log("喵喵") } else if(animal instanceof Wolf) { console.log("嗷嗷") } } function Dog() {} function Cat() {} function Wolf() {} makeSound(new Dog()) makeSound(new Cat()) makeSound(new Wolf())
此时咱们须要更改的地方包括新增Wolf,以及更改makeSound函数console
若是是多态方法function
// 多态代码 function makeSound2(animal) { animal.sound() } function Dog2(){} Dog2.prototype.sound = function() { console.log("汪汪汪") } function Cat2(){} Cat2.prototype.sound =function() { console.log("喵喵喵") } function Wolf2(){} Wolf2.prototype.sound =function() { console.log("嗷嗷") } makeSound2(new Dog2()) makeSound2(new Cat2()) makeSound2(new Wolf2())
此时咱们只须要添加一个Wolf2的类便可实现新的需求,而不用去更改makeSound2函数,维护也是一个道理,只需再生成的新实例之间更改;有点相似 让人去干活-----什么人干什么活,突出在这两个过程,而不是将两个过程合二为一class
多态的结构相似将一分为二,提供统一接口,让不一样实例使用这一接口调用不一样的函数扩展