当前位置: 首页> 教育> 大学 > 实现具有多个实现类的接口并为每个实现类定义一个名字的方法

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

时间:2025/7/20 5:26:20来源:https://blog.csdn.net/qq_41358574/article/details/139855305 浏览次数:0次

在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);}
}
关键字:实现具有多个实现类的接口并为每个实现类定义一个名字的方法

版权声明:

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

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

责任编辑: