下面的代碼顯示了一個使用double
點的矩形類,它們也存儲在一個對象中。矩形和矩形中的點是不可變的,因爲它們不需要改變。我想提供複製(創建新的點對象)或引用構造函數中提供的點的功能,但我唯一能想到的方法是添加一個布爾參數,指定調用者是否想要一份副本或參考。可以複製或引用的構造函數
這是爲了擴展性,雖然它可能不是最重要的,我想這個選項。但是,我不喜歡它用布爾參數實現的方式。有沒有辦法讓兩個構造函數可以採用相同的參數,一個是作爲參考,另一個是複製?或者在原型中是否存在與C++參數自動定義等價的內容,因此不需要由調用方指定?我曾經想過用可變參數,但隨後調用者可以發送無限參數垃圾,可能導致堆棧溢出,我想......
/**
* An immutable, double-precision floating-point (64-bit doubles x4) rectangle.
* The rectangle can be made to reference existing points, or to create new points. Since the points
* are also immutable, this is acceptable, as it is guaranteed they cannot change.
* @author Bill
*/
public class DoubleRect {
public final DoublePoint topLeft;
public final DoublePoint bottomRight;
public DoubleRect(DoublePoint setTopLeft, DoublePoint setBottomRight, boolean makeCopies) {
if(makeCopies == true) {
topLeft = new DoublePoint(setTopLeft);
bottomRight = new DoublePoint(setBottomRight);
}
else {
topLeft = setTopLeft;
bottomRight = setBottomRight;
}
}
}
更新:感謝所有幫助我弄清楚怎麼做代替。這是我重新編寫它的方式。
/**
* An immutable, double-precision floating-point (64-bit) rectangle.
* The rectangle can be made to reference existing points, or to create new points. Since the points
* are also immutable, referencing the points is acceptable, as it is guaranteed they cannot change.
* @author Bill
*/
public class DoubleRect {
public final DoublePoint topLeft;
public final DoublePoint bottomRight;
/**
* This constructor will reference the passed objects rather than duplicating them.
* See the static factory method createWithClonedPoints() for making internal copies of the point objects
* @param setTopLeft Double point designating the top left coordinate
* @param setBottomRight Double point designating the bottom right coordinate
*/
public DoubleRect(DoublePoint setTopLeft, DoublePoint setBottomRight) {
topLeft = setTopLeft;
bottomRight = setBottomRight;
}
/**
* This constructor will create new immutable points within this object using the coordinates specified
*/
public DoubleRect(double top, double left, double right, double bottom) {
topLeft = new DoublePoint(left, top);
bottomRight = new DoublePoint(right, bottom);
}
public static DoubleRect createWithClonedPoints(DoublePoint topLeft, DoublePoint bottomRight) {
return new DoubleRect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y);
}
}
如果它們是不可變的,那麼爲什麼要複製? –
還不確定...它用於多線程應用程序,並可能稍後想要在多進程中使用它。我對Java相當陌生,而且我習慣於指針。 –
使用靜態工廠方法。 –