关于工厂设计模式通过反思 [英] Regarding factory design pattern through reflection
问题描述
public abstract class Animal {
public abstract String makeSound();
}
public class Dog extends Animal {
@Override
public String makeSound(){
returnWoof;
}
}
public class Cat extends Animal {
@Override
public String makeSound(){
返回喵;
}
}
public class AnimalFactory {
public Animal getAnimal(String type){
if(canine .equals(type)){
return new Dog();
} else {
返回新的Cat();
}
}
}
public class Main {
public static void main(String [] args){
AnimalFactory animalFactory = new AnimalFactory();
动物a1 = animalFactory.getAnimal(feline);
System.out.println(a1 sound:+ a1.makeSound());
动物a2 = animalFactory.getAnimal(canine);
System.out.println(a2 sound:+ a2.makeSound());
}
}
请告诉我如何添加反射功能进入它,使我不需要甚至确定类型,只是传递类的名称在主java和该子类的对象获得创建
为此,您的 Cat
和 Dog
类必须在自己的文件中在包 your.package
并具有默认构造函数:
public class AnimalFactory {
public Animal getAnimal(String type){
return(Animal)Class.forName(your.package。+ type).newInstance();
}
}
I was doing R&D on factory pattern I have developed the below code ,rite now I know the subclasses are Dog and Cat , but please advise me what to do if the same thing I want to achieve through reflection by passing the class name in main.java
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());
}
}
Please advise it how I can add reflection functionality into it so that I don't need to even determine the type , just pass the class name in the main java and object of that subclass get created
For this to work, your Cat
and Dog
classes must be in their own files in the package your.package
and have default constructors:
public class AnimalFactory {
public Animal getAnimal(String type) {
return (Animal) Class.forName("your.package." + type).newInstance();
}
}
这篇关于关于工厂设计模式通过反思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!