js的策略模式

487 阅读1分钟

定义:定义一系列核心算法,把他们封装起来,并且他们之间可相互替换。就像菜刀和镰刀,应对不同场景而设计的不同工具

核心:将算法使用和算法实现分离开来

案例:s级别有4倍工资,a‘级别3倍工资.b级别2倍工资

普通写法

  var calculate = function (level, salary) {
            if (level == 's') {
                return salary * 4
            }
            if (level == 'a') {
                return salary * 3
            }
            if (level == 'b') {
                return salary * 2
            }
        }
        console.log(calculate('s', 2000));

策略模式(原始状态,适合所有语言)

 var ps = function () {}
        ps.prototype.calculate = function (salary) {
            return salary * 4
        }
        var pa = function () {}
        pa.prototype.calculate = function (salary) {
            return salary * 3
        }
        var pb = function () {}
        pb.prototype.calculate = function (salary) {
            return salary * 2
        }
        var Bouns = function () {
            this.salary = null //初始薪水,
            this.strategy = null //绩效的策略对象
        }
        Bouns.prototype.setSalary = function (salary) {
            this.salary = salary
        }
        Bouns.prototype.setStrategy = function (strategy) {
            this.strategy = strategy
        }
        Bouns.prototype.getBouns = function () {
            return this.strategy.calculate(this.salary)
        }
        var bouns = new Bouns()
        bouns.setSalary(10000)
        bouns.setStrategy(new ps())
        console.log(bouns.getBouns());

js中函数也是对象,万物皆可对象??所以可写成

 var strategies = {
            "s": function (salary) {
                return salary * 4
            },
            "a": function (salary) {
                return salary * 3
            },
            "b": function (salary) {
                return salary * 2
            }
        }
        var getBouns = function (level, salary) {
            return strategies[leval](salary)
        }
        console.log(getBouns('s', 10000));