0

So we have goods and goods have prices. I'd like to calculate the price of goods.

First version (switch):

int getPrice(String name){
   switch(name){
      case "Apple": return 20;
      case "Banana": return 100;
      ... 
   }
}

Second version (map):

Map<String, Integer> prices = new HashMap<String, Integer>;    

int getPrice(String name){
    return prices.get(name);
}

So how this method (or design pattern) is called? Has it a special name?

user2693979
  • 2,482
  • 4
  • 24
  • 23

3 Answers3

3

I would say this is a special case of a lookup table. I would not call it a design pattern because those are larger and more abstract. This is an implementation detail.

For example this can be used in the strategy pattern:

static KnotStrategy getKnotStrategy(String name) {
    switch(name.toLowerCase()) {
        case "slip":   return new SlipKnot();
        case "granny": return new GrannyKnot();
        case "bowline" return new BowlineKnot();

        default: throw new IllegalArgumentException();
    }
}

As opposed to the lookup:

static final Map<String, Supplier<KnotStrategy>> KNOTS = (
    new HashMap<String, Supplier<KnotStrategy>>()
);
static {
    KNOTS.put("slip", SlipKnot::new);
    KNOTS.put("granny", GrannyKnot::new);
    KNOTS.put("bowline", BowlineKnot::new);
}

static KnotStrategy getKnotStrategy(String name) {
    Supplier<KnotStrategy> supp = KNOTS.get(name);
    if(supp != null) {
        return supp.get();
    }

    throw new IllegalArgumentException();
}

But it's not part of the strategy pattern.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
  • Thanks, it's a very good illustration. What it is? SlipKnot::new – user2693979 Feb 21 '14 at 22:40
  • It's nifty Java 8 syntax. It's shorthand for a lambda reference to a constructor. `SlipKnot::new` is shorthand for `() -> new SlipKnot()` which is in turn shorthand for creating a [Supplier](http://download.java.net/jdk8/docs/api/java/util/function/Supplier.html) that returns `new SlipKnot()` in `get`. See [Method References](http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html) for the preview tutorial. – Radiodef Feb 21 '14 at 22:43
0

What you have described is not a design pattern. It's simply a different way to achieve the same goal.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
0

This is not a design pattern. What you are doing is using a data structure instead of a method. In my opinion, due to what you want to do is only map elements with prices, the best way to do it is with your second version. Using a HashMap is a good way to address what you want to do.

Fabian Rivera
  • 1,138
  • 7
  • 15