js原生设计模式——12装饰者模式

1、面向对象模式装饰者

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>面向对象—Decorator装饰者模式</title>
    <script type="text/javascript">
    //给实例对象(注:不影响类)动态添加职责的方式叫做Decorator装饰者模式,较继承,此方法更为灵活。
    //先声明一个原始飞机类
    var Plane = function(){};
    Plane.prototype.fire = function(){
        console.log('发射子弹');
    }
    //接下来声明两个装饰类,他们之间靠this所指向的实例对象连接
    var MissleDecorator = function(plane){//发射导弹装饰类
        this.plane = plane;
    }
    MissleDecorator.prototype.fire = function(){
        this.plane.fire();
        console.log('发射导弹');
    }
    var AtomDecorator = function(plane){//发射原子弹装饰类
        this.plane = plane;
    }
    AtomDecorator.prototype.fire = function(){
        this.plane.fire();
        console.log('发射原子弹');
    }
    //测试用例
    var plane = new Plane();
    plane = new MissleDecorator(plane);//技巧在于这里的实例传参,起到纽带作用
    plane = new AtomDecorator(plane);
    plane.fire();
    //本例已经通过验证
    </script>
</head>
<body>
</body>
</html>

2、函数式编程实现装饰者效果——其实是职责链模式

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"></meta>
    <title>函数式编程实现装饰者效果——其实是职责链模式</title>
</head>
<body>

</body>
<script type="text/javascript">
    var plane = {   //声明单体对象plane
        fire:function(){
            console.log('发射子弹');
        }
    }
    var missleDecortor = function(){   //声明“发射导弹”功能函数
        console.log('发射导弹');
    }
    var atomDecortor = function(){   //声明“发射原子弹”功能函数
        console.log('发射原子弹');
    }
    //缓存原plane对象的fire模块
    var fire1 = plane.fire;
    //重写,拓展plane.fire
    plane.fire = function(){
        fire1();
        missleDecortor();   //拓展发射导弹功能
    }
    //再次缓存,再次重写
    var fire2 = plane.fire;
    plane.fire = function(){
        fire2();
        atomDecortor();
    }
    plane.fire();
</script>
</html>