我有2個課程如下::
ItemA {
// varibales and methods.
}
ItemB{
// varibales and methods.
}
我在服務類中有一個方法:
public Map<String, ItemDetails> getItemDetails(Map<String, ItemA> itemMap, String itemType){
// do something
}
現在我需要根據呼叫者中的某些條件傳遞 ItemA 或 ItemB 。在任何一種情況下,回傳型別都不會改變。我如何使用泛型或通配符來做到這一點。
這就是我想要實作的目標:
public Map<String, ItemDetails> getItemDetails(Map<String, ?> itemMap, String itemType){
// do something
}
以上是處理這種情況的好方法還是請提出更好的方法。我是仿制藥新手,所以需要你的幫助。
uj5u.com熱心網友回復:
我認為多型性和泛型的組合可能是要走的路。
考慮擁有一個介面Item并相應地更改您的類
interface Item {
// TODO: declare methods common for all items
}
class ItemA implements Item {
// TODO: implement the interface
}
class ItemB implements Item {
// TODO: implement the interface
}
那么你的方法會變成
public Map<String, ItemDetails> getItemDetails(Map<String, Item> items) {
// TODO: implement the method body
}
但要注意基于型別別的撰寫條件,因為它是一種常見的反模式
即最好避免這樣的代碼
// anti pattern, should be avoided
if (item instanceof ItemA) {
// do one thing
} else if (item instanceof ItemB) {
// do another thing
}
uj5u.com熱心網友回復:
如果這適合您的用例,您可以創建一個介面Item,同時ItemA實作ItemB并將您的地圖定義為 。Map<String, Item>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456089.html
下一篇:洗掉合并排序的鏈表中的重復項
