zoukankan      html  css  js  c++  java
  • js装饰器模式

    // 装饰器模式 运行时动态添加附加功能到对象中
    /**
     * 1 当我们有这样一个场景:一个笔 造价是一元钱
     * 如果跨省买这只笔增加一元钱运费
     * 如果零售增值2元
     * 如果打八折
     */
    //es6实现
    class Pen {
        // 添加静态方法
        static decorate() {
            return {
                kuasheng: {
                    getPrice(price) {
                        return price + 1;
                    }
                },
                lingshou: {
                    getPrice(price) {
                        return price +2;
                    }
                },
                dazhe: {
                    getPrice(price) {
                        return price * .8;
                    }
                }
            }
        }
        constructor(price) {
            this.price = price; //类的实例属性初始化价格
            this.decorate_list = [];// 存放装饰器的数组
        }
        decorate(decorate) { // 类提供的装饰方法
            this.decorate_list.push(decorate);
        }
        getPrice() {
            let price = this.price;
            this.decorate_list.forEach(res => {
                price = Pen.decorate()[res].getPrice(price);
            })
            return price;
        }

    }
    let pen = new Pen(1);// 出厂价是一元钱 这里可以自定义
    pen.decorate('lingshou');// 让它零售
    pen.decorate('kuasheng');// 让它跨省
    console.log(pen.getPrice());// 4
    let pen2 = new Pen(1);
    pen2.decorate('lingshou');// 让它零售
    pen2.decorate('kuasheng');// 让它跨省
    pen2.decorate('dazhe');// 让它打折
    console.log(pen2.getPrice());// 3.2
  • 相关阅读:
    Python 列表元素排重uniq
    Python正则表达式汇总
    Python 正则表达式:只要整数和小数
    c++写入txt文件
    OpenMP求完数
    Python分割list
    用ConfigParser模块读写配置文件——Python
    Python 正则表达式
    教程和工具--用wxPython编写GUI程序的
    matlab 之字体调整
  • 原文地址:https://www.cnblogs.com/windcat/p/12740390.html
Copyright © 2011-2022 走看看