代码设计模式

文章目录

概要

工厂模式和模板模式

其实目前工厂模式和模板模式一直搞得不太清楚, 粗略写下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());

相关推荐
啦啦啦啦啦zzzz12 小时前
工具:动态类工厂和用配置文件存储属性
c++·设计模式·工具·动态工厂
Nontee17 小时前
设计模式:模板方法与策略,从“每个字都认识“到能说清它们在干嘛
java·数据库·设计模式
choumin19 小时前
行为型模式——模板方法模式
c++·设计模式·模板方法模式·行为型模式
啦啦啦啦啦zzzz1 天前
设计模式:建造者模式
c++·设计模式·建造者模式
梓仁沐白1 天前
【Agent 设计模式】推理技术
设计模式
Kinghiee1 天前
从使用场景切入前端常见设计模式
前端·设计模式
啦啦啦啦啦zzzz2 天前
设计模式:单例模式和工厂模式
c++·单例模式·设计模式·工厂模式
小白说大模型2 天前
Python 工程化设计模式:AI 项目中的异步流水线与策略模式实战
人工智能·python·设计模式
choumin2 天前
行为型模式——中介者模式
c++·设计模式·中介者模式·行为型模式
geovindu3 天前
Java: Chain of Responsibility Pattern
java·开发语言·后端·设计模式·责任链模式·行为模式