[英]Interface implementation and common function
我有以下要求,
對不起,我找不到定義問題的簡單方法。 感覺就像是spring框架提供的解決方案。 但是我需要知道如何從Java / C#應用程序中實現這一點。
聽起來您想要一個實現通用功能的抽象類,但是對於不同的功能仍然有兩個具體的類。 您可能也可能不想保留界面。 因此,選項為:
Interface
^
|
Abstract
class
^
/ \
Concrete Concrete
class 1 class 2
要不就
Abstract
class
^
/ \
Concrete Concrete
class 1 class 2
想要使用這些類的代碼僅使用接口或抽象類。 如何配置要使用的具體類取決於您的確切要求-但大概您已經在較早版本中解決了這一問題。
常見的模式是:
許多JDK類都可以做到這一點。 例如, List<T>
接口具有AbstractList<T>
抽象類,該抽象類被擴展為提供ArrayList<T>
和LinkedList<T>
。
一個簡單的(如果有人為的)示例將類似於:
interface IntThingy {
int getValue();
int getDoubeValue();
}
abstract class AbstractIntThingy implements IntThingy {
@Override
public int getDoubleValue() {
return getValue() * 2;
}
}
class ConstantFourtyTwo extends AbstractIntThingy {
@Override
public int getValue() {
return 42;
}
}
class ConstantIntThingy extends AbstractIntThingy {
private final int value;
ConstantIntThingy(int value) {
this.value = value;
}
@Override
public int getValue() {
return value;
}
}
請注意,一旦Java 8到來,您就可以在接口中定義方法。 這些通常稱為“防御者方法”。 發生這種情況時,您可能不需要抽象類-取決於該通用功能是否需要維持其自己的狀態(接口仍然無法定義實例狀態)。 但是就目前而言,界面抽象的模式通常效果很好。
您可以嘗試避免使用簡單的界面並使用策略模式:
創建一個實現您的接口並包含“通用功能”的具體類(或更好的抽象類),現在您可以使用兩個(或更多)類來擴展該類(層次結構)。
設計此需求的方法還有很多。 而且我也不確定我的最好。
只是為了補充Jon Skeet的答案,您需要考慮您的類與接口或預期的抽象類之間的關系。 如果接口之間的行為之間的關系為has-a,則接口是正確的選擇;如果接口為is-a,則可以使用抽象類。
在另一種情況下,您還可以檢查該關系是否為has-a,並且要實現的新通用功能是is-a關系,那么除了Jon的選擇之外,您還可以使用以下方法:
Abstract
class
^
/ \
Interface Interface
\ /
Concrete Concrete
class 1 class 2
例如:
interface IParent{}
abstract class Parent{}
class Child1: Parent, IParent{}
class Child2: Parent, IParent{}
這完全取決於您如何設計類以供將來使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.