在使用工厂模式时,通常需要创建多个不同的类实例。这些类可能有许多相同的特性和行为,我们可以使用继承来避免重复代码。以下是在Typescript中使用继承改进工厂模式的示例:
首先,我们创建一个抽象的“Animal”类,它包含所有动物的共有属性和方法:
export abstract class Animal {
name!: string;
abstract makeSound(): void;
move(distance: number): void {
console.log(`${this.name} moved ${distance} meters`);
}
}
然后,我们创建两个具体的动物子类,分别为“Cat”和“Dog”:
export class Cat extends Animal {
makeSound(): void {
console.log("Meow Meow");
}
}
export class Dog extends Animal {
makeSound(): void {
console.log("Woof Woof");
}
}
接下来,我们重构之前的工厂函数,使其返回“Animal”类的实例,而不是不同的子类实例。
export function createAnimal(type: string): Animal {
switch (type) {
case "cat":
return new Cat();
case "dog":
return new Dog();
default:
throw new Error("Invalid type");
}
}
现在,我们可以使用该函数来创建不同类型的“Animal”类实例,如下所示:
const myCat = createAnimal("cat");
myCat.name = "Tom";
myCat.move(10);
myCat.makeSound(); //Output: "Meow Meow"
const myDog = createAnimal("dog");
myDog.name = "Scooby";
myDog.move(20);
myDog.makeSound(); //Output: "Woof Woof"
这种方法使用继承来避免代码重复,并且我们可以轻松地添加新类型的“Animal”类实例,而不必更改工厂函数的代码。