当前位置: 首页 > news >正文

实现具有多个实现类的接口并为每个实现类定义一个名字的方法

在Java中,实现具有多个实现类的接口并为每个实现类定义一个名字的方法,可以通过使用工厂模式或服务定位器模式来完成。以下是使用工厂模式的一个示例:
定义接口和实现类
首先,定义一个接口和多个实现类:

// 接口
public interface ServiceInterface {void serve();
}// 实现类1
public class ServiceImpl1 implements ServiceInterface {@Overridepublic void serve() {System.out.println("Serve method of ServiceImpl1");}
}// 实现类2
public class ServiceImpl2 implements ServiceInterface {@Overridepublic void serve() {System.out.println("Serve method of ServiceImpl2");}
}

创建工厂类
然后,创建一个工厂类来根据给定的名字实例化相应的实现类:

public class ServiceFactory {public static ServiceInterface getService(String name) {switch (name) {case "Impl1":return new ServiceImpl1();case "Impl2":return new ServiceImpl2();default:throw new IllegalArgumentException("Unknown service implementation: " + name);}}
}

使用工厂类:

public class Main {public static void main(String[] args) {// 获取实现类实例ServiceInterface service1 = ServiceFactory.getService("Impl1");service1.serve(); // 输出: Serve method of ServiceImpl1ServiceInterface service2 = ServiceFactory.getService("Impl2");service2.serve(); // 输出: Serve method of ServiceImpl2}
}

方法二:
注册机制。可以定义一个hashmap,每个实现类注册自身到工厂,这里要用到spring的initializingBean:
工厂类:

public class ClusterFactory {// 处理类Mapprivate static final Map<String, ClusterHandler> CLUSTER_FACTORY = new HashMap<>(8);// 获取处理类public static ClusterHandler get(String type) {return CLUSTER_FACTORY.get(type);}// 注册处理类public static void register(String type, ClusterHandler clusterHandler) {if (null == type) {return;}CLUSTER_FACTORY.put(type, clusterHandler);}
}

实现类:

//一个实现类
@Service
@Slf4j
public class CloudClusterHandler extends ClusterHandler {@Overridepublic void afterPropertiesSet() {ClusterFactory.register(ClusterTypeEnum.CLOUD.getName(), this);}
}
http://www.lryc.cn/news/379348.html

相关文章:

  • Linux解压缩命令
  • 如何在 Ubuntu 14.04 上使用 Iptables 实现基本防火墙模板
  • jasypt对yml文件进行加密解密
  • vue3-openlayers 使用tianditu,wmts和xyz等source加载天地图切片服务
  • npm、yarn、pnpm 最新国内镜像源设置和常见问题解决
  • Qt Object:智能即时聊天室项目
  • php,python aes加密反解
  • 基于Java学生选课管理系统设计和实现(源码+LW+调试文档+讲解等)
  • 阅读笔记——《Large Language Model guided Protocol Fuzzing》
  • C#委托:事件驱动编程的基石
  • Git的下载安装及可视化工具小乌龟
  • 【面试实战】# 并发编程之线程池配置实战
  • Pytest 读取excel文件参数化应用
  • qt 一个可以拖拽的矩形
  • C# 启动exe 程序
  • Netty中的Reactor模型实现
  • dll丢失应该怎么解决,总结5种解决DLL丢失问题的方法
  • dial tcp 10.96.0.1:443: connect: no route to host
  • VScode创建ROS项目 ROS集成开发环境
  • nodejs从基础到实战学习笔记-nodejs简介
  • 2024年最新版------二进制安装部署Kubernetes(K8S)集群
  • 【mysql】关键词搜索实现
  • Python面试十问2
  • C# OpenCvSharp 图像处理函数-颜色通道-cvtColor
  • 总结之LangChain(三)——模型IO缓存
  • 判断一个Java服务是不是GateWay
  • 三次插值曲线--插值技术
  • python循环结构
  • 深入理解Netty的Pipeline机制:原理与实践详解
  • 直方图均衡化示例