欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > 工厂模式加策略模式 -- 具体实现

工厂模式加策略模式 -- 具体实现

2025/3/11 21:35:15 来源:https://blog.csdn.net/weixin_44550490/article/details/146154975  浏览:    关键词:工厂模式加策略模式 -- 具体实现

这里写目录标题

      • 定义接口
      • 定义抽象类
      • 定义主处理器
      • 分支处理器
      • 定义工厂
      • demo

在这里插入图片描述

定义接口

public interface EntityHandler extends InitializingBean {MatchContentDTO match(MatchEntityDTO matchEntityDTO);String supportEntityType();
}

定义抽象类

public abstract class AbstractEntityHandler implements EntityHandler {@Overridepublic final MatchContentDTO match(MatchEntityDTO matchEntityDTO) {EntityHandler specialMatchHandler = getSpecialMatchHandler(matchEntityDTO);if (specialMatchHandler != null) {return specialMatchHandler.match(matchEntityDTO);}return doCommonMatch(matchEntityDTO);}public abstract MatchContentDTO doCommonMatch(MatchEntityDTO matchEntityDTO);public EntityHandler getSpecialMatchHandler(MatchEntityDTO matchEntityDTO) {return null;}}

定义主处理器


@Service
@Slf4j
public class EntitySystemHandler extends AbstractEntityHandler {@Overridepublic MatchContentDTO doCommonMatch(MatchEntityDTO matchEntityDTO) {log.info("EntitySystemHandler:{}", JSON.toJSONString(matchEntityDTO));return new MatchContentDTO();}@Overridepublic String supportEntityType() {return this.getClass().getName();}@Overridepublic void afterPropertiesSet() throws Exception {EntityFactory.register(this);}@Overridepublic EntityHandler getSpecialMatchHandler(MatchEntityDTO matchEntityDTO) {return super.getSpecialMatchHandler(matchEntityDTO);}
}

分支处理器

@Service
@Slf4j
public class TimeEntityHandler extends AbstractEntityHandler {@Overridepublic String supportEntityType() {return  this.getClass().getName();}@Overridepublic MatchContentDTO doCommonMatch(MatchEntityDTO matchEntityDTO) {log.info("TimeEntityHandler:{}", JSON.toJSONString(matchEntityDTO));return new MatchContentDTO();}@Overridepublic void afterPropertiesSet() throws Exception {EntityFactory.register(this);}
}

定义工厂

public class EntityFactory{private static final Map<String, EntityHandler> ENTITY_HANDLER_MAP = new HashMap<>();public static EntityHandler getEntityHandler(String entityType){return ENTITY_HANDLER_MAP.get(entityType);}public static void register(EntityHandler handler) {if (handler == null) {return;}ENTITY_HANDLER_MAP.put(handler.supportEntityType(), handler);}}

demo


@SpringBootTest
@RunWith(SpringRunner.class)
public class EntityTest {@Testpublic  void  getTest(){EntityHandler entityHandler = EntityFactory.getEntityHandler("system");MatchEntityDTO matchEntityDTO = new MatchEntityDTO();entityHandler.match(matchEntityDTO);}
}

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词