簡體   English   中英

Java擴展了通用原型

[英]Java extends generic prototype

我有幾個實現一些接口的類。 現在我想創建一個新類,它可以在使用接口方法時根據運行時計算擴展其中一個類。 我們在代碼中談談:

public interface Interface {
    public void doSomething();
}

public class A implements Interface {
    @Override
    public void doSomething() {
        System.out.println("hello");
    }
}

public class B implements Interface {
    @Override
    public void doSomething() {
        System.out.println("hi");
    }
}

這些是現有的類,所以現在我需要做這樣的事情(當然不行):

public class C<T extends Interface> extends T {
    public void doSomethingElse() {
        this.doSomething();
    }

    public static void main(String[] args) {
        C c;
        if(isSomethingLoaded) {
            c = new C<A>();
        } else {
            c = new C<B>();
        }
        c.doSomethingElse();
    }
}

有可能以某種方式,除了我將參數接口傳遞給C的構造函數和存儲到類屬性的方式..?

類不能從其類型參數擴展。

使用組合而不是繼承:

public class C<T extends Interface> {
    private final T foo;

    public C(T foo){
       this.foo = foo;
    }

    public void doSomethingElse() {
        foo.doSomething();
    }

    public static void main(String[] args) {
        C<?> c;
        if(isSomethingLoaded) {
            c = new C<>(new A());
        } else {
            c = new C<>(new B());
        }
        c.doSomethingElse();
    }
}

您甚至可能不需要此處的type參數,只需使用接口類型作為參數/成員類型。

我認為這樣的情況說明了為什么我們有依賴於繼承的組合規則。 使用組合考慮此解決方案:

public class Test {
    public interface Interface {
        void doSomething();
    }

    public static class A implements Interface {
        @Override
        public void doSomething() {
            System.out.println("Doing A");
        }
    }

    public static class B implements Interface {
        @Override
        public void doSomething() {
            System.out.println("Doing B");
        }
    }

    public static class C implements Interface {
        private Interface composedWith;

        public C(Interface i) {
            this.composedWith = i;
        }

        @Override
        public void doSomething() {
            this.composedWith.doSomething();
        }
    }

    public static void main(String[] args) {
        C c;
        if(isSomethingLoaded) {
            c = new C(new A());
        } else {
            c = new C(new B());
        }
        c.doSomething();
    }
}

就個人而言,我覺得這是一個更清晰,更靈活的方式來實現你想要做的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM