且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带抽象参数和继承的Java抽象方法

更新时间:2022-04-05 02:08:05

instanceof 通常可以通过使用访问者模式来避免。根据您的需要,它可能是也可能不是过度的l。它很灵活但很冗长。在下面的示例中,我从 A 中删除​​了 abstract ,以说明它如何与不同类型一起使用。

instanceof can usually be avoided by using the visitor pattern. Depending on your needs, it may or may not be an overkill. It's flexible but quite verbose. In the example below I removed abstract from A to illustrate how it works with different types.

诀窍是,当要求对象访问访问者时,对象本身会在访问者中选择正确的 accept 方法。 instanceof-check通过多态解决。 (我怀疑它比 instanceof 更有效。)

The trick is that when an object is asked to visit a visitor, the object itself chooses the correct accept method in the visitor. The "instanceof"-check is resolved through polymorphism. (I doubt that it's more efficient than an instanceof though.)

interface Visitor {
    public A accept(A a);
    public B accept(B b);
}

class A {
    public A sum(A a) {
        System.out.println("A.sum(A) called");
        return null;
    }

    public A visit(Visitor sv) {
        return sv.accept(this);
    }
}

class B extends A {
    public B sum(B b) {
        System.out.println("B.sum(B) called");
        return null;
    }

    public B visit(Visitor sv) {
        return sv.accept(this);
    }
}

public class Test {

    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        A basa = new B();

        a.visit(new SumVisitor(b));        // a.sum(b);
        b.visit(new SumVisitor(b));        // b.sum(b);
        basa.visit(new SumVisitor(b));     // basa.sum(b);
        basa.visit(new SumVisitor(basa));  // basa.sum(basa);
    }

    static class SumVisitor implements Visitor {
        A arg;
        SumVisitor(A arg) { this.arg = arg; }
        public A accept(A a) { return a.sum(arg); }
        public B accept(B b) { return b.sum(arg); }
    }
}

输出:

A.sum(A) called
B.sum(B) called
B.sum(B) called
B.sum(B) called

Disclamer;不久前我写了一个访问者,所以如果我在这个(几乎未经测试的)代码片段中有任何错误,请纠正我。或者更好,自己编辑帖子并改进它:)

Disclamer; It was a while ago I wrote a visitor, so please correct me if I have any bugs in this (almost untested) code snippet. Or better, edit the post yourself and improve it :)