/**
* 实体类:Dog、Cat
*/
class Dog {
run() {
console.log("狗");
}
}
class Cat {
run() {
console.log("猫");
}
}
/**
* 工厂类:Animal
*/
class Animal {
constructor(name) {
name = name.toLocaleLowerCase();
switch (name) {
case "dog":
return new Dog();
case "cat":
return new Cat();
default:
throw TypeError("class name wrong");
}
}
}
/**
* 以下是测试代码
*/
const cat = new Animal("cat");
cat.run();
const dog = new Animal("dog");
dog.run();