class Hotel {
static final Map<String, List<String>> mapInformation = {
'Americana Hotel': [
'4.3*',
'\$4000 / Night',
],
};
String getPrice(String favouriteElementsName) {
return mapInformation[favouriteElementsName]?.elementAt(1) ??
'It may need fixes';
}
String getRating(String favouriteElementsName) {
return mapInformation[favouriteElementsName]?.elementAt(0) ??
'It may need fixes';
}
}
class Home {
static final Map<String, List<String>> mapInformation = {
'Beachside Resort': [
'2.2*',
'\$2200 / Night',
],
};
String getPrice(String favouriteElementsName) {
return mapInformation[favouriteElementsName]?.elementAt(1) ??
'It may need fixes';
}
String getRating(String favouriteElementsName) {
return mapInformation[favouriteElementsName]?.elementAt(0) ??
'It may need fixes';
}
}
class Favourite {
final LinkedHashMap<String, dynamic> favouriteElementsInLinkedHashMap =
LinkedHashMap();
void changePrice(String favouriteElementKey, Object obj) {
obj.mapInformation[favouriteElementKey]?[1] = '\$5000 / Night';
var str1 = obj.getPrice(favouriteElementKey);
var str2 = obj.getRating(favouriteElementKey);
}
void main() {
var fav = Favourite();
favouriteElementsInLinkedHashMap['Americana Hotel'] = Hotel;
favouriteElementsInLinkedHashMap['Beachside Resort'] = Home;
for (var mapKey in favouriteElementsInLinkedHashMap.keys) {
fav.changePrice(
mapKey, favouriteElementsInLinkedHashMap[mapKey]);
}
}
}
有方法changePrice,当我使用mapInformation时它给我一个错误,有什么办法,我如何在方法changePrice中使用mapInformation,getPrice,getRating。有很多类别,如酒店和家庭。所以我不能在方法changePrice中使用if,else。
创建一个定义这些方法的抽象类:
abstract class Accommodation {
String getPrice(String favouriteElementsName);
String getRating(String favouriteElementsName);
}
现在
Hotel
和 Home
都应该扩展该抽象类,并用 @override
注释重写方法:
class Hotel extends Accommodation {
@override
String getPrice(String favouriteElementsName) {
// ...
}
// Do the same for other overriding methods
}
class Home extends Accommodation {
// Do the same as Hotel
}
更改
obj
参数的类型:
void changePrice(String favouriteElementKey, Accommodation obj) {
// ...
}