[英]A function that are existing only in one concrete implementation of an interface
我有一個帶有一種方法的接口:
public interface MyInterface {
public void doSomething();
}
以及“MyInterface”的多個具體實現:
實施1:
public class Implementation1 implements MyInterface {
@Override
public void doSomething() {
// DO something for implementation1
}
}
實施2:
public class Implementation2 implements MyInterface {
@Override
public void doSomething() {
// DO something for implementation2
}
}
和實施3:
public class Implementation3 implements MyInterface {
@Override
public void doSomething() {
// DO something for implementation3
}
public void doSomething(int something) {
// DO something for implementation3
}
}
如果我想使用 'MyInterface' 類型訪問 'doSomething(10)' 我需要將此 function 添加到 'MyInterface' 和其他實現(在我的示例中為 'Implementation1' 和 'Implementation2' )必須實現此 ZC1C425268E68385D1AB4ZZC17A94F 但什么也不做,因為我在“實施1”和“實施2”中不需要這個function。
我的問題是:在這種情況下如何進行? 實現'doSomething(int something)'並讓他們在'Implementation1'和'Implementation2'中只為'Implementation3'或將實例變量轉換為'Implementation3'並以這種方式創建對具體類型'Implementation3'的依賴關系? 我想指定我不想創建對具體實現的依賴,因為我想讓接口相互通信。
謝謝!
一種解決方案是擁有 2 個接口,第一個是您已經擁有的:
public interface MyInterface {
void doSomething();
}
第二個從第一個擴展,因此它已經具有無參數方法以及采用 int 參數的第二個方法重載:
// already has the default method
public interface MyInterface2 extends MyInterface {
void doSomething(int value);
}
那么如果一個具體的 class 需要這兩種方法,它可以實現第二個接口:
public class Implementation3 implements MyInterface2 {
@Override
public void doSomething() {
// DO something for implementation3
}
@Override
public void doSomething(int something) {
// DO something for implementation3
}
}
請注意,上述 class 的實例仍然可以在需要 MyInterface 類型的地方使用。
我想澄清一下情況。 您有一個接口,它代表一種行為,在您的情況下,MyInterface 代表所有 object 可以在沒有任何輸入參數的情況下做某事。 之后,您希望您的某些對象具有另一種行為:帶 int 輸入參數的 doSomething。 您可以創建具有 doSomething(int value) 的新接口,並且只有 Implementation3 實現它。
public interface MyInterface2 {
void doSomething(int something);
}
public class Implementation3 implements MyInterface, MyInterface2 {
@Override
public void doSomething() {
// DO something for implementation3
}
@Override
public void doSomething(int something) {
// DO something for implementation3
}
}
您可以將 MyInterface2.doSomething(1) 與所有 class 實現的 MyInterface2 一起使用。 我希望它有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.