我来自C ++,我试图在Java中继承Generic参数类型。基本上,我试图模仿下面的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()..
}
}
这种模式叫什么?我称之为&#34; Base Factory&#34;模式,但我不确定它的真实名称,所以我不确定要搜索什么..
我怎样才能在Java中用C ++做同样的事情?有没有&#34;任何方式&#34;在Java中做同样的模式?
答案 0 :(得分:1)
不,不能在java中这样做,抱歉。最接近的可能是&#34;委托模式&#34;:
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中,你可以使它看起来更好(但效率可能更低),而不需要额外的接口和类:
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());