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

在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);
    }
}
相关推荐
动感小麦兜4 分钟前
NAS学习
java·开发语言·eureka
小安同学iter21 分钟前
天机学堂day05
java·开发语言·spring boot·分布式·后端·spring cloud·微服务
那我掉的头发算什么21 分钟前
【javaEE】文件&IO--文件内容操作
java·java-ee·文件·文件操作
c骑着乌龟追兔子27 分钟前
Day 32 函数专题1:函数定义与参数
开发语言·前端·javascript
yaoxin52112329 分钟前
262. Java 集合 - Java 中 ArrayList 与 LinkedList 读取元素性能大对决
java·开发语言
椰萝Yerosius31 分钟前
MATLAB简介
开发语言·数学建模·matlab
大迪吃小迪34 分钟前
Vert.x 常见问题精简总结
java·websocket·web
李日灐40 分钟前
C++STL:list(双链表)的底层实现 && 部分源码解析
开发语言·c++
毕设源码-钟学长1 小时前
【开题答辩全过程】以 农村困境儿童帮扶助学系统为例,包含答辩的问题和答案
java·eclipse
无限进步_1 小时前
C语言宏的魔法:探索offsetof与位交换的奇妙世界
c语言·开发语言·windows·后端·算法·visual studio