策略模式

  

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const price=(function(){
            const tactics={
                '100-10':function(price){return price-parseInt(price/100)*10},
                '200-20':function(price){return price-Math.floor(price/200)*20},
                '80%':function(price){return price*0.8}
            }
            function calculate(price,tactic){
                if(!tactics[tactic]) return 'tactic not found'
                return tactics[tactic](price)
            }

            calculate.add=function(tactic,action){
                if(tactics[tactic]){
                    if(confirm(`replace ${tactic}`)){
                        tactics[tactic]=action
                    }
                }
                tactics[tactic]=action
            }
            calculate.remove=(tactic)=>{
                if(!tactics[tactic]) return 'tactic not found'
                delete tactics[tactic]
            }
            return calculate
        })()

        console.log(price(320,'100-10'))
    </script>
</body>
</html>

 

上一篇:响应式介绍


下一篇:java Random.nextInt()方法