我在工厂模式上做R& D我已经开发了以下代码,请根据工厂模式的功能告知它是否正确..
public abstract class Animal {
public abstract String makeSound();
}
public class Dog extends Animal {
@Override
public String makeSound() {
return "Woof";
}
}
public class Cat extends Animal {
@Override
public String makeSound() {
return "Meow";
}
}
public class AnimalFactory {
public Animal getAnimal(String type) {
if ("canine".equals(type)) {
return new Dog();
} else {
return new Cat();
}
}
}
public class Main {
public static void main(String[] args) {
AnimalFactory animalFactory = new AnimalFactory();
Animal a1 = animalFactory.getAnimal("feline");
System.out.println("a1 sound: " + a1.makeSound());
Animal a2 = animalFactory.getAnimal("canine");
System.out.println("a2 sound: " + a2.makeSound());
}
}
请根据工厂模式的设计告知它是否正确,我可以进一步改进吗
答案 0 :(得分:3)
如果传入类名,则可以避免类型检查:
public class AnimalFactory {
public Animal getAnimal(String className) throws Exception {
Class animalClass = Class.forName(className);
return animalClass.newInstance();
}
}