该设计模式如何称呼? (用地图代替开关) [英] How is this design pattern called? (map instead of switch)

查看:102
本文介绍了该设计模式如何称呼? (用地图代替开关)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我们有商品,商品有价格。
我想计算商品价格。

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

第一个版本(切换):

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

第二版(地图):

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?

推荐答案

我会说这是查找表。我不会将其称为设计模式,因为它们更大且更抽象。这是一个实现细节。

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

与查找相反:

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.

这篇关于该设计模式如何称呼? (用地图代替开关)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆