Java 扩展通用类型参数

Java extend Generic Type Parameter

我来自 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中是否有"any way"做同样的模式?

不,不能在 java 中执行此操作,抱歉。最接近的可能是 "delegate pattern":

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());