class Polygon { . . public int getPerimeter() {...} public boolean isConvex() {...} public boolean containsPoint(Point p) {...} . . }
并將其更改為類似以下的形式:
class Polygon { . . public int getPerimeter() {return pPolygon.computePerimeter(this);} public boolean isConvex() {return pPolygon.isConvex(this);} public boolean containsPoint(Point p) {return pPolygon.containsPoint(this, p);} . . }
其中,pPolygon 如下所示:
class pPolygon { static public int computePerimeter(Polygon polygon) {...} static public boolean isConvex(Polygon polygon) {...} static public boolean containsPoint(Polygon polygon, Point p) {...} }
第二步:將非基本數(shù)據(jù)類型的輸入?yún)?shù)類型轉(zhuǎn)換為接口類型 通過(guò)接口參數(shù)類型而非通過(guò)類繼續(xù)利用多態(tài)性,這是在面向?qū)ο缶幊谭椒ㄖ袑?shí)現(xiàn)可重用性的真正基礎(chǔ),正如 Allen Holub 在 "Build User Interfaces for Object-Oriented Systems, Part 2" 中所講的那樣。
您也可能有過(guò)多次這樣的經(jīng)歷,即最好創(chuàng)建一個(gè)獨(dú)特的接口來(lái)指定單個(gè)過(guò)程對(duì)一個(gè)參數(shù)的要求。您所創(chuàng)建的接口只會(huì)用于那個(gè)參數(shù)。當(dāng)您希望將參數(shù)當(dāng)作 C 中的函數(shù)指針處理時(shí)經(jīng)常會(huì)出現(xiàn)這種情況,例如,假定有這樣一個(gè)過(guò)程:
static public void sort(List list, SortComparison comp) {...}