gpt4 book ai didi

Java 扩展泛型类型参数

转载 作者:行者123 更新时间:2023-11-30 05:48:56 26 4
gpt4 key购买 nike

我来自 C++,我正在尝试继承 Java 中的通用参数类型。基本上,我正在尝试模拟以下 C++ 模式:

在 C++ 中,我可以:

#include <iostream>

class Node
{
Node* next;
};


class BaseVisitor
{
public:
BaseVisitor(Node* ptr)
{
std::cout<<ptr<<"\n\n";
delete ptr;
}
~BaseVisitor() {};

protected:
virtual Node* Generate() = 0;
};


class DynamicVisitor : public BaseVisitor
{
public:
DynamicVisitor(Node* ptr) : BaseVisitor(ptr) {}

protected:
virtual Node* Generate()
{
std::cout<<"Dynamic Visitor\n";
return new Node();
}
};

class StaticVisitor : public BaseVisitor
{
public:
StaticVisitor(Node* ptr) : BaseVisitor(ptr) {}

protected:
virtual Node* Generate()
{
std::cout<<"Static Visitor\n";
return NULL;
}
};



template<typename T>
class TestVisitor : public T //THIS is where the magic happens..
{
public:
TestVisitor() : T(this->Generate()) {} //allows me to call "Generate".
};

int main()
{
TestVisitor<DynamicVisitor> foo = TestVisitor<DynamicVisitor>();
TestVisitor<StaticVisitor> bar = TestVisitor<StaticVisitor>();
}

输出:

Dynamic Visitor
0x605ed0

Static Visitor
NULL

如何在 Java 中做同样的事情?我试过:

public class Node {
Node next;
}

public abstract class BaseVisitor {
public BaseVisitor(Node n) {System.out.println(n);}

protected abstract Node generate();
}

public class DynamicVisitor extends BaseVisitor {
public DynamicVisitor(Node n) {
super(n);
}

@Override
protected Node generate() {
return new Node();
}
}

public class StaticVisitor extends BaseVisitor {

public StaticVisitor(Node n) {
super(n);
}

@Override
protected Node generate() {
return null;
}
}

public class TestVisitor<T extends BaseVisitor> extends T { //error.. Cannot extend "T".. No magic happens..
public TestVisitor() {
super(this.generate()); //cannot call generate()..
}
}
  1. 这个模式叫什么?我称它为“Base Factory”模式,但我不确定它的真实名称,所以我不确定要搜索什么..

  2. 如何在 Java 中完成与 C++ 中相同的操作?在 Java 中是否有“任何方式”来执行相同的模式?

最佳答案

不,不能在 java 中执行此操作,抱歉。最接近的可能是“委托(delegate)模式”:

public interface NodeGenerator {  Node generate(); }
public class StaticGenerator implements NodeGenerator {
public Node generate() { return null; }
}
public class DynamicGenerator implements NodeGenerator {
public Node generate() { return new Node(); }
}

public class TestVisitor extends BaseVisitor {
public TestVisitor(NodeGenerator g) { super(g.generate()); }
}

在 java 8 中,您可以使它看起来更好(但可能效率较低),而无需额外的接口(interface)和类:

public class TestVisitor extends BaseVisitor {
public TestVisitor(Supplier<Node> g) { super(g.get()); }
}

// ... and then you can do things like

TestVisitor staticVisitor = new TestVisitor(() -> null);
TestVisitor dynamicVisitor = new TestVisitor(() -> new Node());

关于Java 扩展泛型类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27974745/

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