SpringBoot工厂模式

前言

下面的示例展示了 SpringBoot 中如何使用工厂模式,该示例通过 ApplicationContext 直接获取 Spring 容器中所有 Animal 的 Bean,然后将它们存储在 animalMap 中,使用时直接从 Map 中获取实例。

另一种工厂模式可参考我另一篇文章 :SpringBoot 工厂模式自动注入到Map

一、建立父类

java 复制代码
public abstract class Animal {
    public abstract void makeSound();
    public abstract String getType();
}

二、两个子类

java 复制代码
@Component
public class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Miao!");
    }

    @Override
    public String getType() {
        return "cat";
    }
}
java 复制代码
@Component
public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Wang!");
    }

    @Override
    public String getType() {
        return "dog";
    }
}

三、工厂类注入到 map 里

java 复制代码
@Component
public class AnimalFactory implements ApplicationContextAware, InitializingBean {
    private final Map<String, Animal> animalMap = new ConcurrentHashMap<>();

    private ApplicationContext appContext;

    public Animal getAnimal(String animalType) {
        Animal animal = this.animalMap.get(animalType);
        if (animal == null) {
            throw new IllegalArgumentException("Unsupported animal type: " + animalType);
        }
        return animal;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, Animal> beansOfType = this.appContext.getBeansOfType(Animal.class);
        beansOfType.values().forEach(animal -> animalMap.put(animal.getType(), animal));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.appContext = applicationContext;
    }
}

四、测试

java 复制代码
	@Autowired
    private AnimalFactory animalFactory;
	
	
    public void printSound() throws Exception {
        Animal animal_1 = animalFactory.getAnimal("dog");
        animal_1.makeSound(); // 输出 "Wang!"

        Animal animal_2 = animalFactory.getAnimal("cat");
        animal_2.makeSound(); // 输出 "Miao!"
    }
相关推荐
爱上妖精的尾巴6 分钟前
8-8 WPS JS宏 正则表达式 字符组与任选
java·服务器·前端
一嘴一个橘子16 分钟前
mybatis-plus 基于 service 接口的 crud
java
Java小卷1 小时前
KIE Drools 10.x 规则引擎快速入门
java·后端
fengsen52113141 小时前
Windows操作系统部署Tomcat详细讲解
java·windows·tomcat
竟未曾年少轻狂1 小时前
Spring Boot 项目集成 Redis
java·spring boot·redis·缓存·消息队列·wpf·redis集群
_codemonster1 小时前
java web修改了文件和新建了文件需要注意的问题
java·开发语言·前端
Java天梯之路1 小时前
Spring Boot 钩子全集实战(九):`@PostConstruct` 详解
java·spring boot·后端
十间fish1 小时前
车载大端序和tcp大端序
后端
松涛和鸣1 小时前
75、 IMX6ULL LM75温度传感器I2C驱动开发
java·linux·数据库·驱动开发·python
独自破碎E1 小时前
BISHI41 【模板】整除分块
java·开发语言