• JavaScript 模拟策略模式


    /**
     * 模拟一个接口,其方法会抛出异常;
     */
    function FlyInter () {}
    FlyInter.prototype.fly = function() {
        throw '实现这个接口';
    };
    /**
     * 实现一个fly noway的方法;
     */
    function FlyNoWays() {}
    FlyNoWays.prototype.fly = function() {
        console.log('fly noways');
    };
    /**
     * 实现一个fly with Wings的方法;
     */
    function FlyWithWings () {}
    FlyWithWings.prototype.fly = function() {
        console.log('fly with wings');
    };
    /**
     * 鸭子超类;构造函数中设置了一个接口;
     */
    function Duck() {
        this.flyI = new FlyInter();
    }
    Duck.prototype.swim = function() {
        console.log('duck can swim');
    };
    /**
     * fly方法调用flyI接口的fly方法;
     */
    Duck.prototype.fly = function() {
        this.flyI.fly();
    };
    /**
     * RubberDuck继承Duck;构造函数中设置自己的fly对象;
     */
    function RubberDuck () {
        this.flyI = new FlyNoWays();
    }
    RubberDuck.prototype = new Duck();
    RubberDuck.prototype.constructor = RubberDuck;
    delete RubberDuck.prototype.flyI;
    
    var rDuck = new RubberDuck();
    //直接调用Duck中的fly()方法即可;
    rDuck.fly();
  • 相关阅读:
    令我印象最深刻的三个老师
    硬盘大于2T安装CentOS7.X时要注意分区
    Linux网卡配置
    Python13:文件操作
    Python12:集合
    Python11:字典
    Python10:String字符串
    Python09:元组
    Python08:列表
    Python07:模块初识
  • 原文地址:https://www.cnblogs.com/stono/p/4379811.html
Copyright © 2020-2023  润新知