/**
* @author beck.yang
* @date 2022/6/27 18:40
* @description
*/
public class Main {
public static void main(String[] args) {
Pet cat = PetFactory.createPet(Cat.class);
cat.eat();
Pet dog = PetFactory.createPet(Dog.class);
dog.eat();
}
}
public class PetFactory{
public static <T extends Pet> T createPet(Class<T> clazz){
Pet pet = null;
try {
pet= (Pet) Class.forName(clazz.getName()).getDeclaredConstructor().newInstance();
}catch (Exception e){
System.out.println("Pet生成错误!");
e.printStackTrace();
}
return (T) pet;
}
}
/**
* @author beck.yang
* @date 2022/6/27 18:34
* @description 宠物类
*/
public class Pet {
public void eat(){
System.out.println("Pet eat...");
}
}
/**
* @author beck.yang
* @date 2022/6/27 18:29
* @description 狗
*/
public class Dog extends Pet {
@Override
public void eat() {
System.out.println("Dog eat...");
}
}
/**
* @author beck.yang
* @date 2022/6/27 18:29
* @description 猫
*/
public class Cat extends Pet {
@Override
public void eat() {
System.out.println("Cat eat...");
}
}