zoukankan      html  css  js  c++  java
  • 简单工厂模式的实现

    枚举+反射实现简单工厂模式(又叫静态工厂模式)

    定义接口:

    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();
        }
    }

    运行结果:

  • 相关阅读:
    大数据基础——MR编程应用——对中间件的操作
    Hadoop_Hive整理——原理及配置
    Hadoop&Hive——小结
    mysql_小结之事务
    Linux_大数据与数据仓库
    移动布局小结
    JDBC——小结
    Mysql优化反刍
    NoSql-Verson1.0
    python-6
  • 原文地址:https://www.cnblogs.com/chenmz1995/p/10534462.html
Copyright © 2011-2022 走看看