是否可以在 Java 中创建一个使用接口作为参数化类型的静态工厂方法/类并返回该给定接口的实现类?
尽管我对泛型的了解有限,但这是我想做的:
// define a base interface:
public interface Tool {
// nothing here, just the interface.
}
// define a parser tool:
public interface Parser extends Tool {
public ParseObject parse(InputStream is);
}
// define a converter tool:
public interface Converter extends Tool {
public ConvertObject convert(InputStream is, OutputStream os);
}
// define a factory class
public class ToolFactory {
public static <? extends Tool> getInstance(<? extends Tool> tool) {
// what I want this method to return is:
// - ParserImpl class, or
// - ConverterImpl class
// according to the specified interface.
if (tool instanceof Parser) {
return new ParserImpl();
}
if (tool instanceof Converter) {
return new ConverterImpl();
}
}
}
我想限制客户端代码仅将接口“类型”插入从我指定的工具接口扩展的 getInstance() 方法中。这样我就可以确定插入的工具类型是合法工具。
客户端代码应如下所示:
public class App {
public void main(String[] args) {
Parser parser = null;
Converter converter = null;
// ask for a parser implementation (without knowing the implementing class)
parser = ToolFactory.getInstance(parser);
// ask for a converter implementation
converter = ToolFactory.getInstance(converter);
parser.parse(...);
converter.convert(... , ...);
}
}
工厂应该打开接口的类型(不管它是否为空),在工厂询问之前定义。我知道这不会像我写的那样工作,但我希望其中一位读者知道我想要完成什么。
getInstance方法的返回类型和传入的参数一样,所以在传递一个Parser接口的时候,也会返回一个Parser p = new ParserImpl(); 返回 p;
提前感谢您帮助我。