代码设计模式

文章目录

概要

工厂模式和模板模式

其实目前工厂模式和模板模式一直搞得不太清楚, 粗略写下demo示例

就是通过一个入口可以分流去不同方式实现

demo示例

复制代码
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    // 获取某一接口的所有实现类,并通过枚举完成策略模式
    Map<String, TaskService> map = applicationContext.getBeansOfType(TaskService.class);
    taskServiceMap = new HashMap<>();
    map.forEach((key, value) -> {
        for (ContentType contentType : value.getType()) {
            taskServiceMap.put(contentType, value);
        }
    });
}

/**
 * 获取检测服务
 *
 * @param type type
 * @return task service
 */
public TaskService getTaskService(ContentType type) {
    return taskServiceMap.get(type);
}

以上基于的是spring提供的applicationContext.getBeansOfType方法, 他会把全部的重写了某个接口全部的类返回回来

下面另外一种示例, 通过枚举获得类对象

通过Class<? extends IExtractAnimal> extractorClazz; 这种方法保存类对象, 需要的时候通过newInstacnce 创建对象出来

public enum AnimalInfoType {

DOG(".dog", "this is a dog", Dog.class),

CAT(".pptx", "this is a cat", Cat.class),

PIG(".docx", "this is a pig", Pig.class),

复制代码
/**
 * 重量
 */
private String weight;

/**
 * 颜色
 */
private String color;

/**
 * 动物抽取器
 */
private Class<? extends IExtractAnimal> extractorClazz;

FileInfoType(String weight, String color, Class<? extends IExtractAnimal> extractorClazz) {
    this.weight = weight;
    this.color = color;
    this.extractorClazz = extractorClazz;
}

public Class<? extends IExtractAnimal> getExtractorClazz() {
    return extractorClazz;
}

/**
 * 获取动物类型
 *
 * @param filePath fileSuffix
 * @return DocumentType
 */
public static Optional<AnimalInfoType> getFileInfoBySuffix(String weight) {
    for (FileInfoType type : AnimalInfoType.values()) {
        if (weight.endsWith(String.valueOf(type.weight))) {
            return Optional.of(type);
        }
    }
    return Optional.empty();
}

}

public class AnimalFactory {

复制代码
static List<String> supportTypeList = Arrays.asList("dog", "cat", "pig");


public static IExtractFileInfo getInstance(AnimalType animalType) {
    if (animalType == null) {
        return null;
    }       
        return infoType.getExtractorClazz().newInstance();      
}

}

Optional animalInfoType = AnimalInfoType.getFileInfoBySuffix(currentResult.getRealPath());

if (!animalInfoType.isPresent()) {

return;

}

// 根据工厂类获得对应的动物类

IExtractAnimal extractAnimal = AnimalFactory.getInstance(animalInfoType.get());

相关推荐
Carl_奕然2 小时前
【智能体】Agent的四种设计模式之:Multi-Agent Collaboration
设计模式
Lost of 程序猿2 小时前
建造者模式实战:告别“十参数构造函数“的数据导出任务
后端·设计模式·c#·asp.net
SL_staff3 小时前
合规性折旧:当知识资产因主权缺位在审计中‘功能性清零’
java·设计模式·开源
Zane19947 小时前
工厂方法一定比简单工厂高级?三种工厂模式到底该怎么选
设计模式
Hespethorn7 小时前
设计模式是语言缺陷的补丁 —— 从工厂、单例、策略三个模式说起
设计模式
Lost of 程序猿7 小时前
命令模式实战:把“下单后的动作“打包成可执行的任务
后端·设计模式·c#·asp.net·命令模式
一只旭宝7 小时前
【C++复习】四种类型转换 + 常见设计模式 + Redis/MySQL(后端面试复习完整版)
c++·redis·笔记·mysql·设计模式
YYYing.9 小时前
【设计模式系列 (四) 】建造者模式
c++·后端·设计模式·建造者模式·c/c++
Zane19941 天前
同一段单例代码,为什么在高并发下偶尔会创建出两个实例?聊聊哪种单例实现才是真的安全
设计模式
Carl_奕然1 天前
【智能体】Loop 的四种设计模式之:Agent Loop(2026 最新版)
人工智能·设计模式·语言模型