码迷,mamicode.com
首页 > 编程语言 > 详细

javascript——策略模式

时间:2015-07-03 18:54:09      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

<!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>

  

javascript——策略模式

标签:

原文地址:http://www.cnblogs.com/yc-code/p/4619361.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!