javascript——策略模式

<!DOCTYPE html>
<html>
<head>
    <meta content="width =device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="format-detection" content="telephone=no" />
    <title></title>
    <style>
        html, body { margin: 0px; padding: 0px; height: 100%; width: 100%; }
        p { margin: 0px; padding: 0px; }
        .page { width: 100%; height: 100%; }
    </style>
</head>
<body>
    <script>
        //策略模式
        //年终奖demo
        /*
         *根据绩效发放 基本工资*月数=年终奖
         */

        /*-------------js面向对象模式--------------*/
        //策略类
        var performanceS = function () { };//绩效S对象
        performanceS.prototype.calculate = function (salary) {
            return salary * 4;
        }

        var performanceA = function () { }//绩效A对象
        performanceA.prototype.calculate = function (salary) {
            return salary * 3;
        }

        //环境类
        var Bonus = function () {
            this.salary = null;
            this.strategy = null;
        }
        Bonus.prototype.setSalary = function (salary) {
            this.salary = salary;//基本工资
        }
        Bonus.prototype.setStrategy = function (strategy) {
            this.strategy = strategy;//设置策略对象
        }
        Bonus.prototype.getBonus = function () {
            return this.strategy.calculate(this.salary);//返回年终奖
        }

        var bonus = new Bonus();
        bonus.setSalary(1000);
        bonus.setStrategy(new performanceS());
        console.log(bonus.getBonus());


        /*-------------基于js--------------*/
        //策略类
        var strategies = {
            'S': function (salary) {
                return salary * 4;
            },
            'A': function (salary) {
                return salary * 3;
            }
        }
        //环境类
        var calculateBonus = function (level, salary) {
            return strategies[level](salary);
        }
        console.log(calculateBonus('S', 1000));
    </script>
</body>
</html>

  

posted on 2015-07-03 17:54  流浪小白鼠  阅读(130)  评论(0编辑  收藏  举报