java一个接口多个实现得调用

在 Java 中,如果一个接口有多个实现类,可以通过以下几种方式来调用不同的实现类:

  1. 根据具体实现类的类型进行调用:
InterfaceA objA = new ImplementationA();
InterfaceA objB = new ImplementationB();

objA.method(); // 调用 ImplementationA 的实现方法
objB.method(); // 调用 ImplementationB 的实现方法
  1. 利用接口的引用,根据条件判断调用不同的实现类:
InterfaceA obj;
if (condition) {
    obj = new ImplementationA();
} else {
    obj = new ImplementationB();
}

obj.method(); // 根据条件调用不同的实现类方法
  1. 在集合中存储不同的实现类对象,通过循环遍历调用:
List<InterfaceA> objects = new ArrayList<>();
objects.add(new ImplementationA());
objects.add(new ImplementationB());

for (InterfaceA obj : objects) {
    obj.method(); // 循环遍历调用不同实现类的方法
}
  1. 使用工厂模式或依赖注入框架来动态获取不同的实现类对象:
InterfaceA obj = ObjectFactory.getInstance().createInterfaceA();
obj.method(); // 动态获取实现类对象并调用方法

需要根据具体的应用场景和需求选择适合的方式来调用不同的实现类。在代码中,根据接口类型、条件判断、集合遍历或动态获取实例等方式,可以灵活地调用不同的实现类的方法。

,除了上述方案,还有以下一些方案可以实现在 Java 中调用多个实现类:

  1. 使用注解:通过为实现类添加特定的注解,在需要调用的地方通过注解扫描来获取实现类,并进行调用。
  2. 使用代理模式:通过动态代理机制,在运行时生成代理对象,并在代理对象中根据条件调用不同的实现类的方法。
  3. 使用配置文件:将不同实现类的信息配置在文件中,通过读取配置文件来获取实现类,并进行调用。
  4. 使用动态加载:使用 Java 的动态加载机制,根据类名或条件动态加载不同的实现类,并进行调用。

工厂模式得示例代码一

当涉及到工厂模式时,可以按照以下步骤实现:

创建接口:

public interface ProductService {
    void getProductInfo();
}

创建具体的实现类:

public class ProductAService implements ProductService {
    @Override
    public void getProductInfo() {
        System.out.println("Product A info");
    }
}

public class ProductBService implements ProductService {
    @Override
    public void getProductInfo() {
        System.out.println("Product B info");
    }
}

创建工厂类:

public class ProductServiceFactory {
    public static ProductService createProductService(String productType) {
        if (productType.equalsIgnoreCase("A")) {
            return new ProductAService();
        } else if (productType.equalsIgnoreCase("B")) {
            return new ProductBService();
        } else {
            throw new IllegalArgumentException("Invalid product type");
        }
    }
}

使用工厂类获取实例并调用方法:

public class Main {
    public static void main(String[] args) {
        ProductService productServiceA = ProductServiceFactory.createProductService("A");
        productServiceA.getProductInfo(); // 输出:Product A info

        ProductService productServiceB = ProductServiceFactory.createProductService("B");
        productServiceB.getProductInfo(); // 输出:Product B info
    }
}

在上述示例中,通过工厂类的静态方法 createProductService 根据传入的参数(产品类型)动态创建具体的实现类对象。根据不同的产品类型,工厂类返回不同的实例,并通过接口引用调用对应的方法。这样可以在运行时决定具体使用哪个实现类,而无需在代码中直接创建对象。

工厂模式得示例代码(Map实现)二

通过 Map 来实现工厂模式是一种常见的方式,可以将不同的产品类型与对应的实现类进行映射。以下是使用 Map 实现工厂模式的示例代码:

创建接口:

public interface ProductService {
    void getProductInfo();
}

创建具体的实现类:

public class ProductAService implements ProductService {
    @Override
    public void getProductInfo() {
        System.out.println("Product A info");
    }
}

public class ProductBService implements ProductService {
    @Override
    public void getProductInfo() {
        System.out.println("Product B info");
    }
}

创建工厂类:

import java.util.HashMap;
import java.util.Map;

public class ProductServiceFactory {
    private static final Map<String, ProductService> productMap = new HashMap<>();

    static {
        productMap.put("A", new ProductAService());
        productMap.put("B", new ProductBService());
    }

    public static ProductService createProductService(String productType) {
        ProductService productService = productMap.get(productType);
        if (productService == null) {
            throw new IllegalArgumentException("Invalid product type");
        }
        return productService;
    }
}

使用工厂类获取实例并调用方法:

public class Main {
    public static void main(String[] args) {
        ProductService productServiceA = ProductServiceFactory.createProductService("A");
        productServiceA.getProductInfo(); // 输出:Product A info

        ProductService productServiceB = ProductServiceFactory.createProductService("B");
        productServiceB.getProductInfo(); // 输出:Product B info
    }
}

在这个示例中,工厂类通过一个静态的 Map 对象将产品类型与对应的实现类进行映射。在工厂类的 createProductService 方法中,根据传入的产品类型从 Map 中获取对应的实现类实例,并返回给调用方。这样,在运行时可以根据不同的产品类型获取对应的实例对象。

工厂模式得示例代码(注解实现)三

以下是一个使用注解实现多个实现类调用的示例代码:

定义注解:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyImplementation {
    String value();
}

创建接口:

public interface MyInterface {
    void doSomething();
}

创建具体的实现类,并使用注解标记:

@MyImplementation("A")
public class ImplementationA implements MyInterface {
    @Override
    public void doSomething() {
        System.out.println("Implementation A");
    }
}

@MyImplementation("B")
public class ImplementationB implements MyInterface {
    @Override
    public void doSomething() {
        System.out.println("Implementation B");
    }
}

创建工厂类,使用注解扫描获取对应实现类:

import java.util.HashMap;
import java.util.Map;

public class MyFactory {
    private static final Map<String, MyInterface> implementations = new HashMap<>();

    static {
        // 扫描带有@MyImplementation注解的类,并将其实例化并放入implementations Map中
        Reflections reflections = new Reflections("com.example");
        Set<Class<?>> annotatedClasses = reflections.getTypesAnnotatedWith(MyImplementation.class);
        for (Class<?> annotatedClass : annotatedClasses) {
            MyImplementation annotation = annotatedClass.getAnnotation(MyImplementation.class);
            String implementationKey = annotation.value();
            try {
                MyInterface implementation = (MyInterface) annotatedClass.newInstance();
                implementations.put(implementationKey, implementation);
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public static MyInterface getImplementation(String key) {
        return implementations.get(key);
    }
}

使用工厂类获取实例并调用方法:

public class Main {
    public static void main(String[] args) {
        MyInterface implementationA = MyFactory.getImplementation("A");
        implementationA.doSomething(); // 输出:Implementation A

        MyInterface implementationB = MyFactory.getImplementation("B");
        implementationB.doSomething(); // 输出:Implementation B
    }
}

在这个示例中,通过自定义的注解 @MyImplementation 标记具体的实现类,然后使用反射扫描带有该注解的类,并实例化放入工厂类的 implementations Map 中。通过工厂类的 getImplementation 方法,根据指定的实现类标识符获取对应的实现类实例。然后就可以通过实例调用接口定义的方法

工厂模式得示例代码(枚举实现)四

枚举也可以用于实现工厂模式,其中每个枚举常量都代表一个具体的实现类。以下是一个使用枚举实现工厂模式的示例代码:

public interface MyInterface {
    void doSomething();
}

public class ImplementationA implements MyInterface {
    @Override
    public void doSomething() {
        System.out.println("Implementation A");
    }
}

public class ImplementationB implements MyInterface {
    @Override
    public void doSomething() {
        System.out.println("Implementation B");
    }
}

public enum MyFactory {
    IMPLEMENTATION_A {
        @Override
        public MyInterface create() {
            return new ImplementationA();
        }
    },
    IMPLEMENTATION_B {
        @Override
        public MyInterface create() {
            return new ImplementationB();
        }
    };

    public abstract MyInterface create();
}

public class Main {
    public static void main(String[] args) {
        MyInterface implementationA = MyFactory.IMPLEMENTATION_A.create();
        implementationA.doSomething(); // 输出:Implementation A

        MyInterface implementationB = MyFactory.IMPLEMENTATION_B.create();
        implementationB.doSomething(); // 输出:Implementation B
    }
}

在这个示例中,枚举 MyFactory 表示工厂,每个枚举常量代表一个具体的实现类。每个枚举常量都实现了抽象方法 create(),该方法用于创建对应的实现类对象。在 Main 类中,通过枚举常量调用 create() 方法来创建具体的实现类对象,并调用接口方法

  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值