SpringBoot獲取接口的所有實現類以及使用IOC實現最完美的簡單工廠設計模式


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方法非常關鍵

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM