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

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

定义接口和实现类

首先,定义一个接口和多个实现类:

java 复制代码
// 接口
public interface ServiceInterface {
    void serve();
}

// 实现类1
public class ServiceImpl1 implements ServiceInterface {
    @Override
    public void serve() {
        System.out.println("Serve method of ServiceImpl1");
    }
}

// 实现类2
public class ServiceImpl2 implements ServiceInterface {
    @Override
    public void serve() {
        System.out.println("Serve method of ServiceImpl2");
    }
}

创建工厂类

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

java 复制代码
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);
        }
    }
}

使用工厂类:

java 复制代码
public class Main {
    public static void main(String[] args) {
        // 获取实现类实例
        ServiceInterface service1 = ServiceFactory.getService("Impl1");
        service1.serve(); // 输出: Serve method of ServiceImpl1

        ServiceInterface service2 = ServiceFactory.getService("Impl2");
        service2.serve(); // 输出: Serve method of ServiceImpl2
    }
}

方法二:

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

工厂类:

java 复制代码
public class ClusterFactory {

    // 处理类Map
    private 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);
    }
}

实现类:

java 复制代码
//一个实现类
@Service
@Slf4j
public class CloudClusterHandler extends ClusterHandler {

    

    @Override
    public void afterPropertiesSet() {
        ClusterFactory.register(ClusterTypeEnum.CLOUD.getName(), this);
    }
}
相关推荐
C-SDN花园GGbond38 分钟前
【探索数据结构与算法】插入排序:原理、实现与分析(图文详解)
c语言·开发语言·数据结构·排序算法
迷迭所归处2 小时前
C++ —— 关于vector
开发语言·c++·算法
架构文摘JGWZ2 小时前
Java 23 的12 个新特性!!
java·开发语言·学习
leon6252 小时前
优化算法(一)—遗传算法(Genetic Algorithm)附MATLAB程序
开发语言·算法·matlab
拾光师3 小时前
spring获取当前request
java·后端·spring
aPurpleBerry3 小时前
neo4j安装启动教程+对应的jdk配置
java·neo4j
锦亦之22333 小时前
QT+OSG+OSG-earth如何在窗口显示一个地球
开发语言·qt
我是苏苏3 小时前
Web开发:ABP框架2——入门级别的增删改查Demo
java·开发语言
姜太公钓鲸2333 小时前
c++ static(详解)
开发语言·c++
菜菜想进步3 小时前
内存管理(C++版)
c语言·开发语言·c++