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!"
    }
相关推荐
oddsand13 小时前
Redis网络模型
java·数据库·redis
皮卡祺q3 小时前
【redies0-导论】分布式系统的演进-引进redis原因
java·数据库·redis
roman_日积跬步-终至千里3 小时前
如何分析复杂架构:一套真正能落地的方法
java·开发语言·架构
geovindu3 小时前
go: Semaphore Pattern
开发语言·后端·设计模式·golang·企业级信号量模式
IT_陈寒3 小时前
Redis内存用爆了,原来我们都忽略了这个配置
前端·人工智能·后端
武子康3 小时前
Java-02 深入浅出MyBatis 3 快速入门:环境配置、项目创建与 CRUD 操作
java·后端
Don.TIk3 小时前
ChapterOne-搭建项目骨架
java·spring·spring cloud·mybatis
Don.TIk3 小时前
ChaperTwo-整合 SaToken 实现 JWT 登录功能
java·开发语言
qq_2518364573 小时前
基于java Web汽车销售管理系统设计与实现
java·前端·汽车
南极企鹅3 小时前
事务&@Transactional注解
java·数据库·spring·oracle·mybatis