ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

JavaScript 模拟策略模式

2021-06-01 15:03:39  阅读:273  来源: 互联网

标签:fly function RubberDuck flyI JavaScript 模式 Duck prototype 模拟


/**
 * 模拟一个接口,其方法会抛出异常;
 */
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();

 

标签:fly,function,RubberDuck,flyI,JavaScript,模式,Duck,prototype,模拟
来源: https://blog.51cto.com/u_15241951/2841072

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有