Loading

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

 

posted @ 2015-03-31 08:15  stono  阅读(193)  评论(0编辑  收藏  举报