zoukankan      html  css  js  c++  java
  • 模式学习(五)--装饰者模式

    function Sale(price){
            this.price = price || 100;
            this.decorators_list = [];// 装饰着列表作为自身的属性
        }
    
        // 追加列表
        Sale.prototype.decorate = function(decorator){
            this.decorators_list.push(decorator);
        };
    
        // getPrice 完成所有工作
        Sale.prototype.getPrice = function(){
            var price = this.price,
                i,
                max = this.decorators_list.length,
                name;
            
            console.log("初始price:", price, "有几个装饰者:", max);// 100   3
    
            for(i = 0; i < max; i++){
                console.log("每次单独的初始price:", price);//  100  105  112.875
                name = this.decorators_list[i];
                console.log("names are as follows::", name);
    
                price = Sale.decorators[name].getPrice(price);
                console.log("every step , this price is changing:",price)
            }
            return price;
        };
    
        Sale.decorators = {};// 子类  decorators 是一个object
    
        Sale.decorators.fedtax = {//  子子类
            getPrice : function(price){
                return price + price * 5 / 100;
            }
        };
    
        Sale.decorators.quebec = {
            getPrice : function(price){
                return price + price * 7.5 / 100;
            }
        };
    
        Sale.decorators.money = {
            getPrice : function(price){
                return "$" + price.toFixed(2);
            }
        };
    
        var sale = new Sale(100);
        sale.decorate('fedtax');
        sale.decorate('quebec');
        sale.decorate('money');
        var a = sale.getPrice();
        console.log(a);

    说明:

      上面是使用列表实现装饰者模式的。

  • 相关阅读:
    RSA
    DES
    MD5
    增删改查
    [转]数据绑定之DataFormatString
    分页通用存储过程(未验证)
    浅谈sql中的in与not in,exists与not exists的区别
    [转]order by 1是什么意思?
    bak骗子公司
    Performance Considerations for Entity Framework 4, 5, and 6
  • 原文地址:https://www.cnblogs.com/chuyu/p/3492615.html
Copyright © 2011-2022 走看看