简单工厂模式的实现

枚举+反射实现简单工厂模式

定义接口:

public interface IAnimal {
    public void eat();
}

具体类:

public class Pig implements IAnimal {
    public void eat() {
        System.out.println("pig eat");
    }
}
public class Dog implements IAnimal {
    public void eat() {
        System.out.println("dong eat");
    }
}

枚举类,设置类对应的类名:

public enum AnimalType {
    DOG("Dog"),
    PIG("Pig");
    private String value;

    private AnimalType(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}

工厂类:

public class SimpleFactory {
    public static IAnimal getInstance(AnimalType animalType) {
        IAnimal animal = null;
        try {
            animal = (IAnimal) Class.forName(animalType.getValue()).newInstance();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return animal;
    }
}

测试案例:

public class SimpleFactoryTest {
    public static void main(String[] args) {
        IAnimal dog = SimpleFactory.getInstance(AnimalType.DOG);
        dog.eat();
        IAnimal pig = SimpleFactory.getInstance(AnimalType.PIG);
        pig.eat();
    }
}

运行结果:

后续有更好的方法会继续更新。

猜你喜欢

转载自www.cnblogs.com/chenmz1995/p/10534462.html