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

    装饰模式是为类添加额外的职责。在我看来,这些职责并不是某一个类特有,需要添加的类都可以添加,每个类没有必要单独添加这个职责。

    下面是我用js实现的装饰模式

    var Employee={
        name: '',
        getName: function(){
            return this.name;
        },
        setName: function(name){
            this.name = name;
        },
        work: function(){}
    }
    
    function CosmeticsSalesEmployee(name){
        this.name = name;
        this.work = function(){
            alert(this.getName() + " 开始销售化妆品!");
        }
    }
    
    function FruitSalesEmployee(name){
        this.name = name;
        this.work = function(){
            alert(this.getName() + " 开始销售水果!");
        }
    }
    
    CosmeticsSalesEmployee.prototype = Employee;
    FruitSalesEmployee.prototype = Employee;
    
    var cosmeticsSalesEmployee1 = new CosmeticsSalesEmployee("小王");
    cosmeticsSalesEmployee1.work();
    //输出: 小王 开始销售化妆品
    var fruitSalesEmployee = new FruitSalesEmployee("小张");
    fruitSalesEmployee.work();
    //输出   小张 开始销售水果
    
    //装饰类
    var Decorator = {
        employee: null,
        setEmployee: function(e){
            this.employee = e;
        },
        getEmployee: function(){
            return this.employee;
        },
        getName: function(){
            return this.employee ? this.employee.getName() : undefined;
        },
        work: function(){
            this.employee && this.employee.work();
        }
    }
    
    function ArrangeGoodDecorator(employee){
        Decorator.setEmployee(employee);
        this.work = function(){
            alert(this.getName() + "开始清扫货架!");
            Decorator.work();
        }
    }
    ArrangeGoodDecorator.prototype = Decorator;
    var employee1 = new ArrangeGoodDecorator(new CosmeticsSalesEmployee("小王"));
    employee1.work();
    //输出:
    //小王开始清扫货架!
    //小王 开始销售化妆品!
    var employee2 = new ArrangeGoodDecorator(new FruitSalesEmployee("小张"));
    employee2.work();
    //小张开始清扫货架!
    //小张 开始销售水果!
  • 相关阅读:
    Coding.net进阶,使用Git管理代码
    经典算法问题
    浅谈三款常用软件
    Coding.net简单使用指南
    湖北宜化总结
    天顺风能经验总结
    Vue中watch的高级用法
    html 锚点三种实现方法
    【机器学习】EM算法详细推导和讲解
    【机器学习】BP神经网络实现手写数字识别
  • 原文地址:https://www.cnblogs.com/oceanxing/p/2682603.html
Copyright © 2011-2022 走看看