设计模式-多态

问题描述:

Animal类里面所有动物都能吃,能走, 但是就叫声不一样。

狗属于动物能走,能吃,叫“汪汪汪”。

猫属于动物能走,能吃,叫喵喵喵。

请实现:实现狗这个类,实现猫这个类(狗类,猫类共同拥有动物的正常吃,正常走)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

interface MakeSound {
sound(): void;
}
class DogSound implements MakeSound {
sound() {
console.log("狗叫汪汪汪");
}
}

class CatSound implements MakeSound {
sound() {
console.log("猫叫喵喵喵");
}
}

class Animals {
makeSound: MakeSound;
eat() {
console.log("都能正常见吃饭");
}
walk() {
console.log("都是四条腿走路");
}
sound() {
this.makeSound.sound();
}
}
class Dog extends Animals {
constructor() {
super();
this.makeSound = new DogSound();
}
}
class Cat extends Animals {
constructor() {
super();
this.makeSound = new CatSound();
}
}