[英]How to implement Map in singleton class?
我的任務是制作一個關於花店的節目。 我必須創建一個類 PriceList,它是一個單例。 我還有以下給定的測試功能主要:
public static void main(String[] args) {
PriceList pl = PriceList.getInstance();
pl.put("rose", 10.0);
pl.put("lilac", 12.0);
pl.put("peony", 8.0);
查看這些 pl.puts(),我決定在類 PriceList 中實現 Map 接口,但我不知道如何實現,因為我只有這個類的一個對象並且它必須是 Map。 我已經寫了這么多,不知道下一步該怎么做:
public class PriceList <String, Double> implements Map <String, Double> {
private static PriceList instance = null;
protected PriceList() {}
public static PriceList getInstance() {
if (instance == null)
instance = new PriceList();
return instance;
}
public void put(String string, double d) {
// TODO Auto-generated method stub
}}
在此先感謝您的幫助!
你的單身人士是正確的! 您可以在類中創建一個 Map 屬性,並將 put 方法委托給 maps 的 put 方法,而不是實現 map 接口。 拿這個例子:
public class PriceList{
private Map<String, Double> map = new HashMap<String, Double>();
private static PriceList instance = null;
private PriceList() {}
public static PriceList getInstance() {
if (instance == null)
instance = new PriceList();
return instance;
}
public void put(String string, double d) {
map.put(string,double);
}
}
有更簡單的方法可以做到這一點:
添加一個帶有屬性 Flower 和 price 的類 PricePerFlower,並在您的 PriceList 類中放置一個 List 作為屬性。
或者只是在您的 PriceList 類中添加一個 Map 屬性。
Map 實現通常非常復雜(至少是高效的)。
如果你絕對必須使用這個大綱( PriceList
作為單例並實現Map
接口),我建議在引擎蓋下使用現有的 Map 實現:
public class PriceList <String, Double> implements Map <String, Double> {
private Map<String, Double> map = new HashMap<>();
private static PriceList instance = null;
protected PriceList() {}
public static PriceList getInstance() {
if (instance == null)
instance = new PriceList();
return instance;
}
public void put(String string, double d) {
map.put(string, d);
}}
public class MyContext {
private static MyContext ourInstance = null;
private HashMap<String, String> translatedValue;
public static MyContext getInstance() {
if (ourInstance == null)
ourInstance = new MyContext();
return ourInstance;
}
private MyContext() {
translatedValue = new HashMap<>();
}
public void addTranslatedValue(String title, String value) {
translatedValue.put(title, value);
}
public String getTranslatedValue(String value) {
return translatedValue.get(value);
}
}
使用
MyContext myContext = MyContext.getInstance(); myContext.addTranslatedValue("Next", valueTranslated); System.out.println(myContext.getTranslatedValue("Next"));
結果
valueTranslated
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.