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

    说明:

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

  • 相关阅读:
    CSP 命令行选项(201403-3)
    ElasticSearch7.10的查询数据-简单查询
    ElasticSearch 种映射参数详解-理论学习02
    Elasticsearch7.10 -理论学习01
    ElasticSearch7.10索引
    ElasticSearch7.10的分词器
    ElasticSearch-7.10安装-2
    ElasticSearch第一天
    Idea的注释配置
    深圳第一站被骗消费3960元
  • 原文地址:https://www.cnblogs.com/chuyu/p/3492615.html
Copyright © 2011-2022 走看看