gpt4 book ai didi

java - 动态调度和通用接口(interface)工厂

转载 作者:行者123 更新时间:2023-11-29 04:54:08 24 4
gpt4 key购买 nike

我应该如何在 Factory 中实现 RequestFactory 接口(interface),以便我可以根据需要创建 StringRequestIntRequest在什么类型上传递?

本质上,我想动态创建参数化抽象类的具体类的实例,这在 Java 中可能吗?

public class Main {

public static void main(String[] args) {
Integer mInt = 10;
String mString = "string";

MyRequest mReq1 = new Factory<>(mString).getRequest();
mReq1.PerformMyRequest();

MyRequest mReq2 = new Factory<>(mInt).getRequest();
mReq2.PerformMyRequest();
}
}

class Factory<T> implements RequestFactory<T> {

private final MyRequest<T> Req;

public Factory(T body) {
Req = create(body);
}

public MyRequest<T> getRequest() {
return Req;
}

@Override
// How do I implement the interface here so
// that correct factory is invoked depending on T
// so that I can return either StringRequest or IntRequest
public MyRequest<T> create(T body) {
return null;
}

}

工厂接口(interface):

// Interface
interface RequestFactory<T> {
MyRequest<T> create(T body);
}
// Concrete specialized factories
class StringFactory implements RequestFactory<String> {
@Override
public StringRequest create(String body) {
return new StringRequest(body);
}
}
class IntFactory implements RequestFactory<Integer> {
@Override
public IntRequest create(Integer body) {
return new IntRequest(body);
}
}

具有两个具体子类的通用抽象类

// ======================================================

// AbstractClass
abstract class MyRequest<T> {
T mVal;

MyRequest(T body) {
mVal = body;
}

public void PerformMyRequest() {
System.out.println("-> From abstract: " + mVal);

}

}
// Concrete classes that I'd like to automatically
// create using the factory above
class StringRequest extends MyRequest<String> {

StringRequest(String body) {
super(body);
}

public void PerformMyRequest() {
super.PerformMyRequest();
System.out.println(" -> From StringRequest");
}
}
class IntRequest extends MyRequest<Integer> {

IntRequest(Integer body) {
super(body);
}

public void PerformMyRequest() {
super.PerformMyRequest();
System.out.println(" -> From IntRequest");
}
}

最佳答案

这是java做不到的。您可以通过编写一个“MetaFactory”(即工厂的工厂)来完成此操作,它会进行类型检查以选择要创建和返回的工厂实现。

public final class RequestMetaFactory {

public RequestFactory<T> newFactory(T req) {
if (req instanceof String) {
return new StringRequestFactory((String)req);
}

if (req instanceof Integer) {
return new IntegerRequestFactory((Integer)req);
}

throw new IllegalArgumentException(req.getClass() + " not a supported arg type");
}

}

通过执行 SPI 查找以查找实际的 RequestFactory 实例并询问每个实例支持的类型,这可以变得更加复杂。

关于java - 动态调度和通用接口(interface)工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34369970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com