[英]what should be the relationship between those classes?
我希望只調用Type.getNo()
方法來獲取一些計算結果。 如果如果if then else
Type.getNo()
中的if then else
塊顯示“從TypeX.getNo()
獲取數據”,則在內部調用TypeX.getNo()
; 然后,將其結果發送到Type.getNo()
,然后Type.getNo()
會將值返回給用戶。 在第二種情況下,將使用TypeY.getNo()
結果。
對於類關系,這些類之間的關系應該是什么? 我以為這似乎extends
關系,但是我對如何實現該方案感到困惑。 為了推進我的項目,我應該使用設計模式來實現嗎? 如果是,哪種設計模式適合這種情況? 我覺得chain of responsibility
看起來很固定,但是在chain of responsibility
,決定權是在第三類上做出的,就我而言,這應該在另一包中。 另一方面,所有決定都應在同一班上進行。 只是返回值將在其他包中可用。
|--------------------|
| Type |
|--------------------|
| +getNo():int |
| |
|--------------------|
|------------------| |----------------------|
| TypeX | | TypeY |
|------------------| |----------------------|
| | | |
| +getNo():int | | +getNo():int |
| | | |
|------------------| |----------------------|
TypeX and TypeY are visible to only to other classes in the same package
使用抽象類Type
和兩個擴展Type
類TypeX
和TypeY
。
Type
abstract class Type {
int no;
int getNo() {
return no;
}
}
TypeX
public class TypeX extends Type {
public TypeX(int no) {
this.no = no;
}
@Override
int getNo() {
System.out.println("TypeX.getNo()");
return no;
}
}
TypeY
public class TypeY extends Type {
public TypeY(int no) {
this.no = no;
}
@Override
int getNo() {
System.out.println("TypeY.getNo()");
return no;
}
}
App
public class App {
public static void main(String[] args) {
Type x = new TypeX(1);
Type y = new TypeY(2);
System.out.println(x.getNo());
System.out.println(y.getNo());
}
}
輸出:
TypeX.getNo()
1
TypeY.getNo()
2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.