Definition: Define a set of core algorithms, encapsulate them, and interchangeable them. Like kitchen knives and scythes, different tools are designed for different situations

Core: Separating algorithm usage from algorithm implementation

Case study: s level has 4 times salary, A ‘level has 3 times salary and B level has 2 times salary

longhand

  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));
Copy the code

Policy Mode (raw state, suitable for all languages)

 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 // Initial salary,
            this.strategy = null // Performance strategy object
        }
        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());
Copy the code

Js functions are also objects, everything can be objects? So it can be written as

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

Copy the code