当前位置: 首页 > article >正文

SpringBoot工厂模式

前言

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

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

一、建立父类

public abstract class Animal {
    public abstract void makeSound();
    public abstract String getType();
}

二、两个子类

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

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

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

三、工厂类注入到 map 里

@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;
    }
}

四、测试


	@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!"
    }

http://www.kler.cn/a/280450.html

相关文章:

  • 23种设计模式详细知识点(软件设计师)
  • 央行沟通与市场影响以日本央行与黄金市场为例
  • World of Warcraft [CLASSIC][80][Grandel] Call to Arms: Strand of the Ancients
  • JavaScript 的进阶概念补充:V8 引擎的垃圾回收机制
  • Qt自定义控件详解
  • Android Audio音量——硬按键调节音量(七)
  • 【blender】一个汉堡包
  • Java-BatchProcessingUtil工具类
  • 数学建模学习(118):牛顿冷却定律的原理解析、案例分析与Python求解
  • 【Leetcode 2068 】 检查两个字符串是否几乎相等 —— 击败100%
  • SSRF漏洞实现
  • XSS LABS - Level 1 过关思路
  • 【代码随想录训练营第42期 Day38打卡 - 动态规划Part6 - LeetCode 322. 零钱兑换 279.完全平方数 139.单词拆分
  • 【硬核】开源的高性能轻量级ORM框架
  • nacos 动态读取nacos配置中心项目配置
  • 数据结构与算法(快速基础C++版)
  • 【2024】Datawhale AI夏令营-从零上手Mobile Agent-Task1笔记
  • SpringBoot + AOP 解决审计日志记录
  • MySQL中处理JSON数据
  • 【自动驾驶】控制算法(四)坐标变换与横向误差微分方程