码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot获取接口的所有实现类以及使用IOC实现最完美的简单工厂设计模式

时间:2021-05-24 09:54:33      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:values   public   inter   tps   参数   exce   text   logs   instance   

SpringBoot获取接口的所有实现类以及使用IOC实现最完美的简单工厂设计模式

本文连接地址:https://www.cnblogs.com/muphy/p/14770494.html

SpringBoot获取接口的所有实现类

此方式主要是针对已经被IOC容器管理的实现类

例子:

//创建Animal接口
public interface Animal{
    String getType();//此方法可以免去工厂模式需要的策略判断
    void eat();
}

//创建Cat类实现Animal接口并使用@Component注解
@Component
public class Cat implements Animal{
    @Override
    public String getType() {
        return "猫";
    }

    @Override
    public void eat() {
        System.out.println("吃耗子");
    }
}

//创建Dog类实现Animal接口并使用@Component注解
@Component
public class Dog implements Animal{
    @Override
    public String getType() {
        return "狗";
    }

    @Override
    public void eat() {
        System.out.println("吃骨头");
    }
}

//AnimalTest测试
public static class AnimalTest implements ApplicationContextAware{
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Collection<Animal> values = applicationContext.getBeansOfType(Animal.class).values();
        //调用每个子类的方法
        values.forEach(c->{
            c.eat();
        });
    }
}

使用IOC实现简单工厂设计模式

传统的工厂设计模式(不管是简单工厂模式、工厂方法模式还是抽象工厂模式),在创建新的接口类型的时候都必须要修改或者增加工厂部分的代码,通过(ioc)控制反转,对象在被创建的时候就(DI)注入到了容器中,其中getType方法实现策略模式功能,只需要结合前一个例子就能直接获取新的接口类型。

接着上面的例子:

//AnimalFactory工厂通过传入的参数获取对应的接口实现类
@Component
public static class AnimalFactory implements ApplicationContextAware {
    private static Map<String, Animal> animalMap;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        animalMap = applicationContext.getBeansOfType(Animal.class).values().stream().collect(Collectors.toMap(Animal::getType, c -> c));
    }

    public static Animal getInstance(String type) {
        return animalMap.get(type);
    }
}

//工厂测试类
@Component
public static class AnimalFactoryTest {
    //@PostConstruct注解作用是容器初始化完成后自动执行此方法
    @PostConstruct
    public void test(){
        Animal animal = AnimalFactory.getInstance("猫");
        animal.eat();//吃耗子
    }
}

由此可见此方法的好处是工厂部分的代码不要用任何改动,只管新增实现类即可,例子中的getType方法非常关键

 

SpringBoot获取接口的所有实现类以及使用IOC实现最完美的简单工厂设计模式

标签:values   public   inter   tps   参数   exce   text   logs   instance   

原文地址:https://www.cnblogs.com/muphy/p/14770494.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!