我想知道如何实现下面的例子。我试图抽象出House的一些核心功能。我遇到了这种情况。
我们假设有一个抽象的Animal类扩展如下所示
abstract class Animal{
constructor(age:number){
this.age = age;
}
age:number;
}
class Dog extends Animal{
constructor(age:number){
super(age);
}
bark(){
console.log("Bark");
}
}
class Cat extends Animal{
constructor(age:number){
super(age);
}
meow(){
console.log("Meow");
}
}
重点是使它成为应用程序的基类,并且许多不同类型的动物园扩展了它及其核心功能
abstract class House{
animals:Animal[];
addAnimal(humanAge:number){
const animalAge = humanAge/7;
// How to add an animal here kind of like animals.push(new Animal(animalAge));
}
}
class DogHouse extends House{
doSomethingElseHERE(){
console.log("Something else")
}
}
new DogHouse().addAnimal(23); //What would be a viable solution to make this work seamlessly in every animal house like this
那么在抽象类 House
中添加函数会有什么好处答案 0 :(得分:2)
您可以使House
通用,而不是Animal
元素类型可以是派生类中的任何类型的动物。此外,如果您需要在基类中创建一个元素,您可以将特定动物的构造函数作为参数传递给基类:
abstract class House<T extends Animal>{
animals: T[];
constructor(private elementCtor: new (age: number) => T) {
}
addAnimal(humanAge: number) {
const animalAge = humanAge / 7;
this.animals.push(new this.elementCtor(animalAge));
}
}
class DogHouse extends House<Dog> {
constructor() {
super(Dog)
}
doSomethingElseHERE() {
console.log("Something else")
}
}
另一种选择是在House
中创建一个抽象方法:
abstract class House{
animals: Animal[];
constructor() {
}
abstract createAnimal(age: number): Animal
addAnimal(humanAge: number) {
const animalAge = humanAge / 7;
this.animals.push(this.createAnimal(animalAge));
}
}
class DogHouse extends House {
createAnimal(age: number): Animal {
return new Dog(age);
}
constructor() {
super()
}
doSomethingElseHERE() {
console.log("Something else")
}
}