簡體   English   中英

我應該選擇哪種參數類型? 擴展父類型或父類型的泛型

[英]Which parameter type should I choose? A generic that extends a supertype or the supertype

下面,我有一個驅動程序,調用了兩個方法。 第一種方法的參數類型是擴展Polygon的通用類型。 第二種方法的參數類型是多邊形。 兩者都要求我強制轉換參數才能調用子類方法。 哪個更好? 為什么我要在另一個上使用?

public class Driver {
        public static void main(String[] args) {

                Square s1;
                try {
                        s1 = new Square(new Point(0,0), new Point(0,1), new Point(1,1), new Point(1,0));
                }
                catch (IllFormedPolygonException e) {
                        System.out.println(e.toString());
                        return;
                }

                System.out.println(s1.toString());
                printArea(s1);
                printArea2(s1);
        }

        public static <T extends Polygon> void printArea(T poly) {
                System.out.println(poly.getArea());

                if (poly instanceof Triangle) {
                        ((Triangle)poly).doTriangleThing();
                }
                else if (poly instanceof Square) {
                        ((Square)poly).doSquareThing();
                }
                else {
                        System.out.println("Is polygon");
                }
        }

        public static void printArea2(Polygon poly) {
                System.out.println(poly.getArea());

                if (poly instanceof Triangle) {
                        ((Triangle)poly).doTriangleThing();
                }
                else if (poly instanceof Square) {
                        ((Square)poly).doSquareThing();
                }
                else {
                        System.out.println("Is polygon");
                }
        }
}

選擇超級類型。 泛型教程

通用方法允許使用類型參數來表示方法的一個或多個參數的類型和/或其返回類型之間的依賴性。 如果沒有這種依賴性,則不應使用通用方法。

如果參數/返回類型之間沒有關系,那么泛型將不添加任何內容。 它只會使代碼更難閱讀,因此應首選更簡單的解決方案。

這里有一個例子,其中一個通用的方法有用的。 假設您有一個采用Polygon並返回一半大小的副本的方法。 因為返回類型與參數類型相同,所以泛型可用於避免在客戶端代碼中進行強制轉換:

public static void main(String[] args) {
    Square square = new Square(0, 0, 10, 10);

    // Without the generic it's necessary to cast the return value
    square = (Square) shrink(square);

    // Cast not needed with generic
    square = shrinkWithGenerics(square);
}

public static Polygon shrink(Polygon poly) {
    // ...
}

public static <T extends Polygon> T shrinkWithGenerics(T poly) {
    // ...
}

正如@teppic所說,實際上沒有理由在這里使用泛型。

就是說,如果您可以訪問PolygonSquareTriangle類,那么我將緊急對其進行重新設計,以使您完全不必編寫instance of

首先在Polygon類中定義printArea() ,並在子類中定義必要的替代,和/或定義可打印多邊形的附加接口。

其次,如果您不能修改這些類或僅修改Polygon類,則仍可以嘗試擴展Polygon類(=使您自己,更聰明)或將其包裝到例如。 綁定了delegate Polygon的SmartPolygon(請參閱https://en.wikipedia.org/wiki/Delegation_(object-oriented_programming)或直接使用getter getPolygon()進行訪問getPolygon() 。然后使用這個新班。

暫無
暫無

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

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