二:策略模式

策略模式之前


/**
 * 策略模式之前
 * <p>
 * 例子:
 * 穿白色的衣服返回口紅100號
 * 穿紅色的衣服返回口紅300號
 * .....
 */
public class NoStrategy {

    public static int getLipstick(String clothes) {

        if ("white".equals(clothes)) {
            return 1;
        } else if ("red".equals(clothes)) {
            return 2;
        } else if ("yellow".equals(clothes)) {
            return 3;
        }
        return 0;
    }
}

策略模式

/**
 * 策略接口
 */
public interface ClothesLipstick {
    int getLipstick();
}


/**
 * 白色衣服策略接口實現(xiàn)
 */
public class WhiteClothesLipstick implements ClothesLipstick {
    @Override
    public int getLipstick() {
        return 1;
    }
}

/**
 * 紅色策略接口模式
 */
public class RedClothesLipstick implements ClothesLipstick {
    @Override
    public int getLipstick() {
        return 2;
    }
}

/**
 * 黃色衣服策略接口實現(xiàn)
 */
public class YellowClothesLipstick implements ClothesLipstick {
    @Override
    public int getLipstick() {
        return 3;
    }
}

使用方式

public class StrategyDemo {

    public static void main(String[] args) {
        noStrategy();
        System.out.println("====");
        strategy();

    }

    /**
     * 不用策略模式
     */
    private static void noStrategy() {
        List<String> clothes = Lists.newArrayList();
        clothes.add("red");
        clothes.add("white");
        clothes.add("yellow");
        clothes.stream().forEach(item -> System.out.println(item + ":" + NoStrategy.getLipstick(item)));

    }

    /**
     * 使用策略模式
     */
    private static void strategy() {

        Map<String, ClothesLipstick> map = Maps.newHashMap();

        map.put("red", new RedClothesLipstick());
        map.put("white", new WhiteClothesLipstick());
        map.put("yellow", new YellowClothesLipstick());

        map.forEach((k, v) -> System.out.println(k + ":" + v.getLipstick()));


    }

}

總結(jié):對修改關(guān)閉,對擴展開放。代碼的擴展性更好

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容