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

在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);
    }
}
相关推荐
zh_xuan2 小时前
kotlin 尾随Lambda表达式函数的常用简写
开发语言·kotlin
码出财富9 小时前
SpringBoot 内置的 20 个高效工具类
java·spring boot·spring cloud·java-ee
沐知全栈开发9 小时前
Perl 数据库连接
开发语言
我是小疯子6610 小时前
Python变量赋值陷阱:浅拷贝VS深拷贝
java·服务器·数据库
森叶10 小时前
Java 比 Python 高性能的原因:重点在高并发方面
java·开发语言·python
二哈喇子!10 小时前
Eclipse中导入外部jar包
java·eclipse·jar
微露清风10 小时前
系统性学习C++-第二十二讲-C++11
java·c++·学习
qq_3168377510 小时前
uni.chooseMedia 读取base64 或 二进制
开发语言·前端·javascript
方圆工作室10 小时前
【C语言图形学】用*号绘制完美圆的三种算法详解与实现【AI】
c语言·开发语言·算法
小二·11 小时前
Python Web 开发进阶实战:混沌工程初探 —— 主动注入故障,构建高韧性系统
开发语言·前端·python