设计模式学习-(6. 原型模式)

原型模式:  个人觉得跟继承里面的  组合继承没什么区别,需要注意的是:

原型模式继承下的对象,他们共享的基类 的protytype的原型函数占据的内存空间是一样,所以动一个就动了所有。

var SuperClass = function ( arg1 , arg2 ) {
        this.val1 = arg1;
        this.arg2 = arg2;
    };
    SuperClass.prototype = {
        fun1 : function(){
            
        },
        fun2 : function () {
            
        }
    };
    
    var SubClass = function ( arg1 , arg2 ) {
        SuperClass.call( this, arg1 , arg2);
    };
    SubClass.prototype = new SuperClass();
    //  重写继承的方法
    SubClass.prototype.fun1 = function () {

    };




 原型继承,其实就是多继承 , 仔细看下感觉跟前面的 建造者模式也有相似之处,由多个对象构成,建造者模式则是通过new 出来的实例化对象更易变通。


//  这里原型继承 是 把每个对象的属性  作为 子类的 原型链。

function prototypeExtend(){
        var F = function(){},
                args = arguments,
                i = 0,
                len = args.length;
        for( ; i<len ; i++ ){
            for( var j in args[i] ){
                F.prototype[j] = args[i][j];
            }
        }
        return new F();
    }
    var s1 = {
        speed : 20,
        swim : function () {
            console.log( '游泳速度' + this.speed );
        }
    },
            s2 = {
                run : function ( n ) {
                    console.log( '奔跑速度:' + n);
                }
            },
            s3 = {
                jump : function () {
                    console.log( 'jump');
                }
            };
    var t = prototypeExtend( s1, s2, s3);
    t.swim();
    t.run( 10 );
    t.jump();


//  多继承, 复制对象的属性到自己身上

// 多继承  复制 多个对象属性
    Object.prototype.mix = function () {
        var i= 0,
                len = arguments.length,
                arg;
        for( ; i<len ; i++ ){
            arg = arguments[i];
            for( var property in  arg ){
                this[property] = arg[property];
            }
        }
    };

    var book1 = {
        color: "bluc"
    },
            book2 = {
                name: "java"
            },
            book3 = {
                price: 100
            };

    book1.mix( book2 , book3 );
    console.log( book1 );


猜你喜欢

转载自blog.csdn.net/zxf13598202302/article/details/79461188