js面向对象系列五之多态

js面向对象系列五之多态

多态字面意思多种状态,指的是不同的对象按照统一接口执行时,产生多种不同的结果即同一个实现接口,使用不同的实例而执行不同的操作。

按照网上看来的一个例子;主人发出一个"叫"的命令,狗发出汪汪的叫声,猫发出喵喵的叫声

常规非多态代码

//非多态代码
 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())

比较而言,多态代码比非多态代码要臃肿,但是多态代码比非多态代码要好扩展和维护

为何这么说,我么如果要添加了个狼的叫声,如果是非多态代码

//非多态代码
 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函数

如果是多态方法


// 多态代码

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函数,维护也是一个道理,只需再生成的新实例之间更改;有点类似    让人去干活-----什么人干什么活,突出在这两个过程,而不是将两个过程合二为一

多态的结构类似将一分为二,提供统一接口,让不同实例使用这一接口调用不同的函数

猜你喜欢

转载自blog.csdn.net/crq131290x/article/details/83587757