如何基于接口实现创建新对象

问题描述 投票:1回答:2

首先,我认为我的问题措辞不佳,但并不真正理解该措辞。

我有一个由多个类实现的启动接口。我想做的是查看是否有一种方法可以创建一个新对象,从而使我被传递给通用接口,然后基于.getClass()。getSimpleName()方法,基于该字符串创建一个新对象。 。

是创建switch case语句的唯一方法吗?由于实现类的数量太多(大约100个左右)。

参考代码:

public interface MyInterface {
  public void someMethod();
}

然后我将有我的实现类:

public class MyClass1 implements MyInterface {
  public void someMethod() { //statements }
}

public class MyClass2 implements MyInterface {
  public void someMethod() { //statements }
}

public class MyClass3 implements MyInterface {
  public void someMethod() { //statements }
}

我最后想要的是另一个类,该类传递了MyInterface类型的参数,从中获取简单名称,并基于该简单名称创建MyClassX的新实例。

public class AnotherClass {
  public void someMethod(MyInterface interface) {
    if (interface == null) {
      System.err.println("Invalid reference!");
      System.exit(-1);
    } else {
      String interfaceName = interface.getClass().getSimpleName();
      /**
       * This is where my problem is!
       */
      MyInterface newInterface = new <interfaceName> // where interfaceName would be MyClass1 or 2 or 3...
    }
  }
}

非常感谢您的帮助!

java interface instance implements
2个回答
0
投票

您可以为此使用反射:

public void someMethod(MyInterface myInterface) {
Class<MyInterface> cl = myInterface.getClass();
MyInteface realImplementationObject = cl.newInstance(); // handle exceptions in try/catch block
}

0
投票

这是许多解决方案中的常见问题。当我面对它时,我从不使用反射,因为如果它是大型项目的一部分,则很难维护。

通常,当您必须基于用户选择来构建对象时,就会出现此问题。您可以尝试使用Decorator模式。因此,不要为每个选项构建不同的对象。您可以根据选择构建单个对象添加功能。例如:

// you have
Pizza defaultPizza = new BoringPizza();

// user add some ingredients
Pizza commonPizza = new WithCheese(defaultPizza);

// more interesting pizza
Pizza myFavorite = new WithMushroom(commonPizza);

// and so on ...

// then, when the user checks the ingredients, he will see what he ordered:
pizza.ingredients();
// this should show cheese, mushroom, etc.

关键是您没有为每个选项创建对象。相反,您将创建具有所需功能的单个对象。每个装饰器都封装一个功能。

© www.soinside.com 2019 - 2024. All rights reserved.