yeti yeti - 21 days ago 5
Java Question

How to implement Map in singleton class?

I have the task to make a program about Florist's. I have to make a class PriceList, which is a singleton. I have also a following given testing function main:

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);


Looking on these pl.puts(), I decided to implement Map interface in class PriceList, but I don't know exactly how to do it, when I have only one object of this class and it has to be a Map. I have already written that much and don't know what to do next:

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

}}


Thanks in advance for any help!

Answer

Your Singleton is correct! Instead of implementing the map interface, you could create a Map attribute inside your class and delegate the put method to the maps'put method. Take this example:

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);       
    }
}